题目:请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路:
先把整个链表从中间分开,分为两段
然后把后面那个链表到过来
最后一一判断对应值是否相等
leetcode源代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//反转链表函数
struct ListNode* reverseList(struct ListNode* Head){
struct ListNode *pr=NULL,*p;
if(Head==NULL)
return NULL;
while (Head->next!=NULL){
p=Head;
Head=Head->next;
p->next=pr;
pr=p;
}
Head->next=pr;
pr=Head;
return pr;
}
bool isPalindrome(struct ListNode* head){
if(head==NULL||head->next==NULL)
return 1;
struct ListNode *p1=head,*p2=head;
//把链表分为两点断并找到中间靠后那一段链表的开头
while(p2->next&&p2->next->next){
p2=p2->next->next;
p1=p1->next;
}
p1=p1->next;
// 调用反转链表函数
p1=reverseList(p1);
//一一判断对应值是否相等
while(p1){
if(p1->val!=head->val)
return 0;
p1=p1->next;
head=head->next;
}
return 1;
}
leetcode标准答案:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverList(struct ListNode* pHead)
{
struct ListNode revertHead;
revertHead.next = NULL;
while (pHead) {
struct ListNode *tmp = pHead->next;
pHead->next = revertHead.next;
revertHead.next = pHead;
pHead = tmp;
}
return revertHead.next;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* fast = head;
struct ListNode* slow = head;
struct ListNode* mid = NULL;
struct ListNode* pHead = head;
if (head == NULL || head->next == NULL) {
return true;
}
while (fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
mid = slow->next;
slow->next = NULL;
mid = reverList(mid);
while (pHead && mid) {
if (pHead->val != mid->val) {
return false;
}
pHead = pHead->next;
mid = mid->next;
}
if (pHead) {
return true;
}
return true;
}