Created
February 22, 2019 07:08
-
-
Save mikeyang01/080f7be2b2a28b71dec7c04a467158e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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