Huge Lemon的博客

回文链表

2020-03-02

LeetCode 234. Palindrome Linked List

题目描述

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

解题思路

1、找中点的同时,将前半部倒序;
2、比较。
时间复杂度:$O(1)$

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/


bool isPalindrome(struct ListNode* head){
if(!head || !head->next)
return true;

struct ListNode *fast = head, *slow = head, *L = malloc(sizeof(struct ListNode));
L->next = NULL;
while(fast && fast->next) {
//找中点
slow = slow->next;
fast = fast->next->next;

//同时对前面进行反转(头插法)
head->next = L->next;
L->next = head;

head = slow;
}

//slow指向后半部分头结点,head指向前半部分头结点
if(fast)
slow = slow->next;
head = L->next;

//前半部分和后半部分进行比较
while(head){
if(head->val != slow->val)
return false;
head = head->next;
slow = slow->next;
}

return true;
}
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏