更新时间:2022-10-03 13:48:33
234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
题目大意:
判断一个单链表是否为回文链表。
思路:
找到链表中间的节点,将链表从中间分为2部分,右半部分进行链表反向转换,然后左半部分和反转后的右半部分链表进行比较。得出结果。
代码如下:
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
/** * Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public :
ListNode * reverseList(ListNode *head) //链表反转
{
ListNode *pre,*next;
pre = NULL;
next = NULL;
while (head)
{
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if ( NULL == head || NULL == head->next)
return true ;
int len = 0;
ListNode *p = head;
while (p)
{
len++;
p = p->next;
}
ListNode * rightListHead;
rightListHead = head;
int leftLen = len / 2;
int rightLen = len - leftLen;
int i = leftLen;
while (i)
{
rightListHead = rightListHead->next;
i--;
}
rightListHead = reverseList(rightListHead);
ListNode * left = head;
ListNode * right = rightListHead;
while (i < leftLen)
{
if (left->val == right->val)
{
left = left->next;
right = right->next;
}
else
{
return false ;
}
i++;
}
return true ;
}
}; |
复习了单链表反转的方法。