Leetcode 234 Palindrome Linked List 链表

判断链表是否是回文。

我直接将链表的一半进行倒置,然后将两半的链表进行比较

 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     bool isPalindrome(ListNode* head) {
12         int ln = 0, i = 0;
13         ListNode* rhead = NULL;
14         ListNode* now, *rnow;
15         for(now = head; now; now = now->next, ++ln);
16         for(now = head; i < ln / 2; ++i){
17             ListNode* tnow = now;
18             now = now->next;
19             tnow->next = rhead;
20             rhead = tnow;
21         }
22         if(ln % 2 == 1){
23             now = now->next;
24         }
25         for(rnow = rhead; now && rnow; rnow = rnow->next, now = now->next){
26             if(rnow->val != now->val) return false;
27         }
28         return true;
29     }
30 };

 

posted @ 2016-03-18 21:53  Breeze0806  阅读(170)  评论(0编辑  收藏  举报