[234]Palindrome Linked List

来源:互联网 发布:linux创建目录命令 编辑:程序博客网 时间:2024/05/17 08:40

【题目描述】

Given a singly linked list, determine if it is a palindrome.

【思路

先用two pointers的方法找到链表中间的指针,然后将链表后面的节点就地反转,然后将前后两段进行比较。

【代码】

/** * 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==NULL||head->next==NULL) return true;        ListNode* slow=head;        ListNode* fast=head;        ListNode* node=head;        while(fast->next!=NULL&&fast->next->next!=NULL){            fast=fast->next->next;            slow=slow->next;        }        ListNode* middle=slow;        ListNode* tmphead=ReverseList(slow->next);        ListNode* current=tmphead;        while(current!=NULL&&node!=NULL){            if(current->val!=node->val) return false;            current=current->next;            node=node->next;        }        return true;   }   ListNode* ReverseList(ListNode* head){       ListNode* tmphead=NULL;       if(head==NULL||head->next==NULL) return head;       ListNode* current=head;       while(current!=NULL){           ListNode* nextnode=current;           current=current->next;           nextnode->next=tmphead;           tmphead=nextnode;       }       return tmphead;   } };


0 0
原创粉丝点击