LeetCode 面试题 02.06. 回文链表

题目链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci/ 

编写一个函数,检查输入的链表是否是回文的。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
 

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

思路:快慢指针找中点将链表分为两部分,再将后半段逆链表,再依次比较。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 bool isPalindrome(struct ListNode* head){
10     if(head==NULL||head->next==NULL) return true;
11     struct ListNode *slow=head,*fast=head;
12     while(fast->next&&fast->next->next){
13         fast=fast->next->next;
14         slow=slow->next;
15     }
16     struct ListNode *cur=slow,*tmp=NULL,*pre=NULL;
17     while(cur){
18         tmp=cur->next;
19         cur->next=pre;
20         pre=cur;
21         cur=tmp;
22     }
23     while(head){
24         if(head->val!=pre->val) return false;
25         head=head->next;
26         pre=pre->next;
27     }
28     return true;
29 }

 

posted @ 2020-02-27 21:48  wydxry  阅读(298)  评论(0编辑  收藏  举报
Live2D