标签:
1. Title
Palindrome Linked List
2. Http address
https://leetcode.com/problems/palindrome-linked-list/
3. The question
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
4. My code(AC)
1 public ListNode getKthNode(ListNode head, int k) 2 { 3 4 int re = 1; 5 ListNode p = head; 6 while( re <= k && p != null) 7 { 8 if( re == k) 9 { 10 return p; 11 } 12 re++; 13 p = p.next; 14 } 15 return null; 16 } 17 public int getLength(ListNode head) 18 { 19 int re = 0; 20 ListNode p = head; 21 while( p != null) 22 { 23 re++; 24 p = p.next; 25 } 26 return re; 27 } 28 29 30 public ListNode revLinked(ListNode head) 31 { 32 ListNode dump = new ListNode(0); 33 ListNode p = head; 34 ListNode tmp = null; 35 while( p != null) 36 { 37 tmp = p.next; 38 p.next = dump.next; 39 dump.next = p; 40 p = tmp; 41 } 42 return dump.next; 43 } 44 45 46 public boolean isPalindrome(ListNode head) { 47 48 if( head == null || head.next == null) 49 return true; 50 51 int len = getLength(head); 52 ListNode p,q; 53 q = getKthNode(head, (len / 2) + 1); 54 q = revLinked(q); 55 p = head; 56 while( q != null && p != null) 57 { 58 if( q.val != p.val) 59 { 60 return false; 61 } 62 p = p.next; 63 q = q.next; 64 } 65 return true; 66 }
标签:
原文地址:http://www.cnblogs.com/ordili/p/4928513.html