Advertisement
tanglinghui

ctciCh2Q7_1

Jun 3rd, 2012
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.56 KB | None | 0 0
  1.     public static boolean isPalindrome(LinkedList list){
  2.         LinkedListNode slow = list.head;
  3.         LinkedListNode fast = list.head;
  4.        
  5.         Stack<Integer> stack = new Stack<Integer>();
  6.         while(fast!=null&&fast.next!=null){
  7.             stack.push(slow.value);
  8.             slow = slow.next;
  9.             fast = fast.next.next;
  10.         }
  11.        
  12.         /*if the length of list is odd*/
  13.         if(fast!=null){
  14.             slow = slow.next;
  15.         }
  16.        
  17.         /*compare elements all the way to the end*/
  18.         while(slow!=null){
  19.             if(slow.value!=stack.pop().intValue()){
  20.                 return false;
  21.             }
  22.             slow = slow.next;
  23.         }
  24.         return true;
  25.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement