234. Palindrome Linked List

来源:互联网 发布:苹果电脑安装软件 编辑:程序博客网 时间:2024/05/01 17:37

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 Listif (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>






0 0
原创粉丝点击