234. 回文链表

 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 //1、快慢指针找中点
10 //2、以中点为起点,对链表进行逆序
11 //3、进行对比
12 class Solution 
13 {
14 public:
15     bool isPalindrome(ListNode* head) 
16     {
17         ListNode* fast = head;
18         ListNode* slow = head;
19         while(fast && fast->next && slow)
20         {
21             fast = fast->next->next;
22             slow = slow->next;
23         }
24 
25         ListNode* new_head =NULL;
26         while(slow)
27         {
28             ListNode* temp = slow->next;
29             slow->next = new_head;
30             new_head = slow;
31             slow = temp;
32         }
33 
34         while(head && new_head)
35         {
36             if(head->val != new_head->val) return false;
37             head = head->next;
38             new_head = new_head->next;
39         }
40         return true;
41     }
42 };

 

posted @ 2020-04-12 17:44  Jinxiaobo0509  阅读(105)  评论(0)    收藏  举报