首页 > 其他 > 详细

[LeetCode] Palindrome Linked List

时间:2015-07-11 18:21:49      阅读:322      评论:0      收藏:0      [点我收藏+]

Palindrome Linked List

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?

将链表拆成两半,后一半反转后与前一半一一对比,最后恢复链表。O(n) time and O(1) space!

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseList(ListNode *head) {
12         ListNode *pre = NULL, *cur = head, *tmp;
13         while (cur != NULL) {
14             tmp = cur->next;
15             cur->next = pre;
16             pre = cur;
17             cur = tmp;
18         }
19         return pre;
20     }
21     bool isPalindrome(ListNode* head) {
22         if (head == NULL || head->next == NULL) return true;
23         ListNode *slow = head, *fast = head->next;
24         while (fast != NULL) {
25             fast = fast->next;
26             if (fast != NULL) fast = fast->next;
27             else break;
28             slow = slow->next;
29         }
30         ListNode *head2 = slow->next;
31         slow->next = NULL;
32         head2 = reverseList(head2);
33         ListNode *l1 = head, *l2 = head2;
34         bool res = true;
35         while (l1 != NULL && l2 != NULL) {
36             if (l1->val != l2->val) {
37                 res = false;
38                 break;
39             } else {
40                 l1 = l1->next;
41                 l2 = l2->next;
42             }
43         }
44         head2 = reverseList(head2);
45         slow->next = head2;
46         return res;
47     }
48 };

 

[LeetCode] Palindrome Linked List

原文:http://www.cnblogs.com/easonliu/p/4639012.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!