LeetCode | Palindrome Linked List

来源:互联网 发布:淘宝怎么手机实名认证 编辑:程序博客网 时间:2024/05/18 02:45

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?


嗯,判断链表是回文。

1、将链表复制一份到另一个反转链表,同时遍历,时间空间O(n)

2、将链表拍成一个数组,遍历数组,时间空间O(n)

3、比较难想到,将数组前一半反转。再判断后一半与反转后的前一半的关系

/** * 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) {        // ListNode root(-1);        // ListNode* cur=&root,*temp=head;                // for(;temp;temp=temp->next){        //     ListNode* node=new ListNode(temp->val);        //     node->next=cur->next;        //     cur->next=node;        // }                // //按照次序比较        // for(ListNode* l1=cur->next,*l2=head;l1 && l1;l1=l1->next,l2=l2->next){        //     if(l1->val !=l2->val) return false;        // }        // return true;                        // //拍成数组        // vector<int> nums;        // for(ListNode* temp=head;temp;temp=temp->next){        //     nums.push_back(temp->val);        // }        // int n=nums.size();        // for(int i=0;i<n/2;i++){        //     if(nums[i]!=nums[n-i-1]) return false;        // }        // return true;                ListNode root(-1);        ListNode* slow,*fast,*cur=&root;        slow=fast=head;        while(fast && fast->next){            fast=fast->next->next;                        ListNode* next=slow->next;            slow->next=cur->next;            cur->next=slow;            slow=next;        }        if(fast) slow=slow->next;                for(ListNode* t=cur->next;slow;slow=slow->next,t=t->next){            if(t->val !=slow->val) return false;        }        return true;            }};


0 0
原创粉丝点击