Palindrome Linked List
Total Accepted: 5466 Total Submissions: 23472My Submissions
Question Solution
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?
Hide Tags
Hide Similar Problems
(E) Palindrome Number (E) Valid Palindrome (E) Reverse Linked List
Have you met this question in a real interview?
Yes
No
这题需要O(n)的计算时间复杂度,需要O(1)的存储空间,所以可以将后半部分链表逆序,再一个个比较
#include<iostream> #include<vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* reversed(ListNode* L1,ListNode* L2) { if(L1==L2) { L1->next==NULL; return L1; } if(L1->next==L2) { L2->next=L1; L1->next=NULL; return L2; } ListNode* ptr1=L1; ListNode* ptr2=ptr1->next; ListNode* ptr3=ptr2->next; while(ptr3!=L2) { ptr2->next=ptr1; ptr1=ptr2; ptr2=ptr3; ptr3=ptr3->next; } ptr2->next=ptr1; ptr1->next=NULL; return ptr2; } bool isPalindrome(ListNode* head) { if(head==NULL) return 0; if(head->next==NULL) return 1; ListNode* ptr1=head; int n=1; while(1) { if(ptr1->next==NULL) break; n++; ptr1=ptr1->next; } int mid=n/2; ListNode* ptr2=head; int jishu=1; while(1) { if(jishu==mid) break; jishu++; ptr2=ptr2->next; } ListNode* ptr3=ptr2->next; ptr1=reversed(ptr3,ptr1); ListNode* ptr0=head; if(n/2==0) { while(ptr1!=NULL) { if(ptr1->next!=ptr0->next) return 0; ptr1=ptr1->next; ptr0=ptr0->next; } return 1; } else { while(ptr1!=ptr3) { if(ptr1->next!=ptr0->next) return 0; ptr1=ptr1->next; ptr0=ptr0->next; } return 1; } } int main() { int vec[20]={-31900,22571,-31634,19735,13748,16612,-28299,-16628,9614,-14444, -14444,9614,-16628,-31900,16612,13748,19735,-31634,22571,-28299}; ListNode* root=new ListNode(-31900); ListNode* ptr1=root; int i=1; while(i<20) { ptr1->next=new ListNode(vec[i]); ptr1=ptr1->next; i++; } cout<<isPalindrome(root)<<endl; }
时间: 2024-10-29 10:46:40