码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Linked List

时间:2015-11-01 21:11:39      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

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     }

 

Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/ordili/p/4928513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!