LeetCode:Palindrome Linked List(回文链表)

来源:互联网 发布:apache atlas 编辑:程序博客网 时间:2024/05/16 09:32

LeetCode:Palindrome Linked List


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?

回文无处不在,还跑到链表去了。
将链表后半部分逆置,然后开始相等性判断。

类似于C写的:
http://blog.csdn.net/bestzem/article/details/51744971


/** * 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) {        if((!head)||(!head->next))  return true;        int n=0,i=0;        for(ListNode *p=head;p!=nullptr;p=p->next,++n);//count node O(n)        ListNode *thead;        int k=(n+1)/2;        for(ListNode *p=head,*pre;p!=nullptr;)//O(n)        {            ++i;            if(i<k)            {                p=p->next;            }            else if(i==k)            {                pre=p;                p=p->next;                pre->next=nullptr;                if(n%2==0)  pre=nullptr;             }            else            {                thead=p;                p=p->next;                thead->next=pre;                pre=thead;//update pre            }        }        for(ListNode *p=head,*p1=thead;p!=nullptr&&p1!=nullptr;p=p->next,p1=p1->next)//O(n/2)        {            if(p->val!=p1->val) return false;        }        return true;    }};

请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false


2016.8.19更新


上面写的方法对链表进行了破坏。下面这个方法使用了O(n/2)的空间,一次遍历O(n)。重点注意他使用一快一慢指针,巧妙地定位在了中间结点。在编写程序的时候要画图review。当然了,还有一种递归方法,首递归将程序深入到中间结点,然后开始和头结点进行同步比较。


class Palindrome {public:    bool isPalindrome(ListNode* pHead) {        // write code here        if(!pHead)  return false;        stack<int> st;        ListNode *slow=pHead,*fast=pHead;        bool bflag{true};//true偶  false奇        while(fast){            if(fast->next){                fast=fast->next->next;//避免将奇数的中间节点压入                st.push(slow->val);            }              else{                fast=fast->next;                bflag=false;            }            slow=slow->next;        }        if(!bflag){            slow=slow->next;            st.pop();        }        while(slow){            if(slow->val==st.top()){                st.pop();                slow=slow->next;             }             else{                return false;             }        }        return true;/*        vector<int> v;        for(ListNode *cur=pHead;cur!=nullptr;cur=cur->next){            v.push_back(cur->val);        }        int sz=v.size();        for(int i=0,j=sz-1;i<j;++i,--j){            if(v[i]!=v[j]){                return false;            }        }        return true;*/    }};
0 0
原创粉丝点击