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: Linked List Two Pointers
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 5 typedef struct ListNode { 6 int val; 7 ListNode *next; 8 }node; 9 10 bool isPalindrome1(ListNode* head); 11 bool isPalindrome2(ListNode* head); 12 ListNode* getMid(ListNode *head); 13 ListNode* reverse(ListNode *node); 14 15 node *create(){//建立 16 node *head,*p,*s; 17 int x,cycle=1; 18 head=new node();//head=(node*)malloc(sizeof(node)); 19 p=head; 20 while(cycle){ 21 cout<<"input data:"; 22 cin>>x; 23 if(x!=0){ 24 s=new node(); 25 s->val=x; 26 p->next=s; 27 p=s; 28 } 29 else cycle=0; 30 } 31 head=head->next; 32 p->next=NULL; 33 return head; 34 } 35 int main(){ 36 node *mynode=create(); 37 cout<<isPalindrome2(mynode); 38 } 39 40 bool isPalindrome1(ListNode* head){ //Runtime:28ms,一次遍历,取出val,装入vector再进行判断 41 if(head==NULL||head->next==NULL)return true; 42 ListNode *node=head; 43 vector<int> vec; 44 while(node!=NULL){ 45 vec.push_back(node->val); 46 node=node->next; 47 } 48 for(int i=0,j=vec.size()-1;i<j;i++,j--){ 49 if(vec[i]!=vec[j])return false; 50 } 51 return true; 52 }; 53 54 bool isPalindrome2(ListNode* head){ //Runtime:28ms,拆分逆转后半链表,再同时遍历两链表 55 if(head==NULL||head->next==NULL)return true; 56 ListNode *mid=getMid(head); 57 ListNode *remid=reverse(mid); 58 while(head&&remid){ 59 if(head->val!=remid->val)return false; 60 head=head->next; 61 remid=remid->next; 62 } 63 return true; 64 }; 65 66 ListNode* getMid(ListNode *head){ 67 ListNode *slow=head,*fast=head; 68 ListNode *preslow; 69 while(fast->next){ 70 fast=fast->next; 71 if(fast->next){ 72 fast=fast->next; 73 preslow=slow; 74 slow=slow->next; 75 }else{ 76 preslow=slow; 77 slow=slow->next; 78 } 79 } 80 preslow->next=NULL; 81 return slow; 82 } 83 ListNode* reverse(ListNode *node){ 84 if(node==NULL||node->next==NULL)return node; 85 ListNode *node1=node,*node2=node1->next,*node3; 86 while(node2){ 87 node3=node2->next; 88 node2->next=node1; 89 node1=node2; 90 node2=node3; 91 } 92 node->next=NULL; 93 return node1; 94 }
时间: 2024-10-29 19:09:56