// need n extra space publicbooleanisPalindrome1(Node head) { Stack<Node> stack = newStack<Node>(); Nodecur= head; while (cur != null) { stack.push(cur); cur = cur.next; } while (head != null) { if (head.value != stack.pop().value) { returnfalse; } head = head.next; } returntrue; }
publicstaticclassNode { publicint value; public Node next;
publicNode(int data) { this.value = data; } }
// need n extra space publicstaticbooleanisPalindrome1(Node head) { Stack<Node> stack = newStack<Node>(); Nodecur= head; while (cur != null) { stack.push(cur); cur = cur.next; } while (head != null) { if (head.value != stack.pop().value) { returnfalse; } head = head.next; } returntrue; }
// need n/2 extra space publicstaticbooleanisPalindrome2(Node head) { if (head == null || head.next == null) { returntrue; } Noderight= head.next; Nodecur= head; while (cur.next != null && cur.next.next != null) { right = right.next; cur = cur.next.next; } Stack<Node> stack = newStack<Node>(); while (right != null) { stack.push(right); right = right.next; } while (!stack.isEmpty()) { if (head.value != stack.pop().value) { returnfalse; } head = head.next; } returntrue; }
// need O(1) extra space publicstaticbooleanisPalindrome3(Node head) { if (head == null || head.next == null) { returntrue; } Noden1= head; Noden2= head; while (n2.next != null && n2.next.next != null) { // find mid node n1 = n1.next; // n1 -> mid n2 = n2.next.next; // n2 -> end } n2 = n1.next; // n2 -> right part first node n1.next = null; // mid.next -> null Noden3=null; while (n2 != null) { // right part convert n3 = n2.next; // n3 -> save next node n2.next = n1; // next of right node convert n1 = n2; // n1 move n2 = n3; // n2 move } n3 = n1; // n3 -> save last node n2 = head;// n2 -> left first node booleanres=true; while (n1 != null && n2 != null) { // check palindrome if (n1.value != n2.value) { res = false; break; } n1 = n1.next; // left to mid n2 = n2.next; // right to mid } n1 = n3.next; n3.next = null; while (n1 != null) { // recover list n2 = n1.next; n1.next = n3; n3 = n1; n1 = n2; } return res; }