Skip to content

Instantly share code, notes, and snippets.

@mikeyang01
Created February 22, 2019 07:08
Show Gist options
  • Select an option

  • Save mikeyang01/080f7be2b2a28b71dec7c04a467158e1 to your computer and use it in GitHub Desktop.

Select an option

Save mikeyang01/080f7be2b2a28b71dec7c04a467158e1 to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class LinkedList_isPalindrome {
public static class Node {
public int val;
public Node next;
// constructor
public Node(int val) {
this.val = val;
}
// for print
@Override
public String toString() {
return Integer.toString(val);
}
}
public static boolean isPalindrome1(Node head) {
if (head == null) {
return false;
}
Stack<Node> stack = new Stack<>();
Node cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
while (head.next != null) {
if (head.val != stack.pop().val)
return false;
head = head.next;
}
return true;
}
public static void printLinkedList(Node head) {
while (head.next != null) {
System.out.print(head.val + "->");
head = head.next;
}
System.out.print(head.val + "->");//for the last one
}
public static void main(String[] args) {
Node node1 = new Node(1);
node1.next = new Node(2);
node1.next.next = new Node(2);
node1.next.next.next = new Node(1);
System.out.println(isPalindrome1(node1));
Node node2 = new Node(1);
node2.next = new Node(2);
node2.next.next = new Node(3);
System.out.println(isPalindrome1(node2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment