Skip to content

Commit ad26bd9

Browse files
authored
Create (链表操作)234、回文链表
1 parent 2532533 commit ad26bd9

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

(链表操作)234、回文链表

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
请判断一个链表是否为回文链表。
3+
4+
示例 1:
5+
6+
输入: 1->2
7+
输出: false
8+
示例 2:
9+
10+
输入: 1->2->2->1
11+
输出: true
12+
进阶:
13+
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
14+
*/
15+
16+
/**
17+
* Definition for singly-linked list.
18+
* struct ListNode {
19+
* int val;
20+
* struct ListNode *next;
21+
* };
22+
*/
23+
24+
struct ListNode* reverseList(struct ListNode* head)
25+
{
26+
struct ListNode* previous = NULL;
27+
struct ListNode* current = head;
28+
while(current != NULL)
29+
{
30+
struct ListNode* tmp = current->next;
31+
current->next = previous;
32+
previous = current;
33+
current = tmp;
34+
}
35+
return previous;
36+
}
37+
bool isPalindrome(struct ListNode* head)
38+
{
39+
if(head == NULL || head->next == NULL)
40+
return true;
41+
struct ListNode* slow = head;
42+
struct ListNode* fast = head;
43+
while(fast != NULL && fast->next != NULL)
44+
{
45+
fast = fast->next->next;
46+
slow = slow->next;
47+
}
48+
struct ListNode* middle = reverseList(slow);
49+
struct ListNode* front = head;
50+
while(middle != NULL)
51+
{
52+
if(front->val != middle->val)
53+
return false;
54+
middle = middle->next;
55+
front = front->next;
56+
}
57+
return true;
58+
}
59+
60+
/*
61+
解题思路:
62+
1、使用快慢指针法找到链表的中间位置(如果是奇数个元素,中间位置为中心元素的后一个元素);
63+
2、对以中间位置元素为起始节点的后半部分链表进行链表反转;
64+
3、将反转后的链表和前半部分链表进行逐个节点比较,如果出现节点对应值不相等的情况,则说明
65+
原链表不是镜像对称的,返回false。
66+
*/

0 commit comments

Comments
 (0)