LeetCode-E-Palindrome Linked List

来源:互联网 发布:js改变style display 编辑:程序博客网 时间:2024/06/13 20:36

题意

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?

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems

解法

双指针,翻转后半段链表,和前半段做对比

实现

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head) {        if(head == NULL || head->next == NULL) return head;        ListNode* cur = head;        while(cur->next != NULL){            ListNode* next = cur->next;            cur->next = next->next;            next->next = head;            head = next;        }        return head;    }    bool isPalindrome(ListNode* head) {        if(head == NULL || head->next == NULL) return true;        ListNode* fast = head;        ListNode* slow = head;        ListNode* pre = NULL;        while(fast != NULL && fast->next != NULL){            fast = fast->next->next;            pre = slow;            slow = slow->next;        }        pre->next = NULL;        if(fast != NULL && fast->next == NULL) slow = slow->next;        ListNode* rhead = reverseList(slow);        ListNode* p = head;        ListNode* q = rhead;        while(q != NULL && p != NULL){            if(p->val != q->val) return false;            p = p->next;            q = q->next;        }        if(q != NULL || p != NULL) return false;        return true;    }};
0 0
原创粉丝点击