Last active
December 13, 2015 18:18
-
-
Save charlespunk/4954140 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
Implement a function to check if a linked list is a palindrome. |
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
//iterative | |
public static boolean checkPalindrome(Node root){ | |
Node slow = root; | |
Node fast = root; | |
Stack<Integer> previousNode = new Stack<>(); | |
while(fast != null && fast.next != null){ | |
previousNode.push(slow.value); | |
slow = slow.next; | |
fast = fast.next.next; | |
} | |
if(fast != null) slow = slow.next; | |
while(slow != null){ | |
if(slow.value != previousNode.pop()) return false; | |
slow = slow.next; | |
} | |
return ture; | |
} |
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
//recursive | |
public static Result checkPalindrome(Node root, int count){ | |
if(root == null || count == 0) return Result(null, false); | |
else if(count == 1) return Result(root.next, true); | |
else if(count == 2) return Result(root.next.next, root.value == root.next.value); | |
Result before = checkPalindrome(root.next, count -2); | |
if(!before.byfar) return Result; | |
else{ | |
Node nextRunner = before.runner.next; | |
return Result(nextRunner, root.value == before.runner.value) | |
} | |
} | |
class Result{ | |
Node runner; | |
boolean byFar; | |
Result(Node r, boolean b){ | |
this.runner = r; | |
this.byfar = b; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment