LeetCode 面试题 02.06. 回文链表

孤街浪徒 提交于 2020-02-27 22:51:17

题目链接: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 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!