Palindrome linked list is a linked list that reads the same fromboth directions (direction 1: from head to tail; direction 2: fromtail to head.)
For example,
It is easy to detect if a doubly linked listis palindrome or not, as you may traverse from either direction.While detecting if a singly linked list ispalindrome or not involves some work, such as using recursion orexplicit LIFO data structure, say stack.
Test your code by passing both steps below.
#include <iostream>
// add any library if needed, say stack
//// linked list stuff begin
struct Node {
int value;
Node* next;
Node(int v) : value{ v }, next{ nullptr } {}
};
typedef Node* NodePtr;
void add_at_head(NodePtr& head, int value) {
NodePtr newNode = new Node{ value };
newNode->next = head;
head = newNode;
}
//// linked list stuff end
// TODO: implement this function
public boolean isPalindrome(Node head) {
}
int main(){
NodePtr list1{};
NodePtr list2{};
for (auto i : {1, 2, 3, 2, 1}) add_at_head(list1, i);
for (auto i : {1, 2, 3, 1, 2}) add_at_head(list2, i);
// step 1: uncomment to print reasult
// expected:
// true
std::cout << std::boolalpha <<palindromeList(list1) << std::endl;
// step 2: uncomment to print reasult
// expected:
// false
// std::cout << std::boolalpha <<palindromeList(list2) << std::endl;
}
for (auto i : {1, 2, 3, 2, 1}) add_at_head(list1, i);
for (auto i : {1, 2, 3, 1, 2}) add_at_head(list2, i);
// step 1: uncomment to print reasult
// expected:
// true
std::cout << std::boolalpha <<palindromeList(list1) << std::endl;
// step 2: uncomment to print reasult
// expected:
// false
// std::cout << std::boolalpha <<palindromeList(list2) << std::endl;
}
PLEASE DO THE TO DO CODE ONLY DO NOT MAKE CHANGES IN THE OTHERPARTS OF THE CODE AND ANSWER IN C++
Palindrome linked list is a linked list that reads the same from both directions (direction 1: from head to tail; direct
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am