您的位置:首页 > 其它

234. Palindrome Linked List

2016-03-24 21:58 295 查看
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?
题意:判断一个单链表是否回文。
思路:先确定链表的长度,然后将链表右半段反转,进行值对比,在把右半段反转回来。

<span style="font-size:14px;">/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
int count = 0;
ListNode* p = head;
while (p){
count++;
p = p->next;
}
if (count <= 1)
return true;
p = head;
for (int i = 0; i < count/2 -1; i++)
p = p->next;
ListNode* q = NULL;
if ((count & 1) == 1){
q = p->next->next;
}
else{
q = p->next;
}
q = reverseList(q);
p = head;
while (p && q){
if (p->val == q->val){
p = p->next;
q = q->next;
}
else{
return false;
}
}
reverseList(q);
return true;
}

ListNode* reverseList(ListNode* head) {//链表反转算法,在206. Reverse Linked List
if (head == NULL)
return head;
ListNode *p, *q, *r;
p = NULL;
q = head;
r = head->next;
while (r){
q->next = p;
p = q;
q = r;
r = r->next;
}
q->next = p;
return q;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: