letecode [234] - Palindrome Linked List

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

题目大意

  判断一个单链表是否为回文链表。

理  解:

  方法一:时间复杂度O(n),空间复杂度O(1)

    计算链表长度,逆置前半部分链表,遍历前后两部分链表,判断元素是否相等。奇数中间节点不用考虑。

  方法二:时间复杂度O(n),空间复杂度O(n)

    使用栈保存前半部分节点,将后半部分值与栈顶元素比较。

代 码 C++:

方法一:

/**
 * 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* p = head;
        ListNode* q = head;
        ListNode* newHead = head;
        int len = 0;
        while(p!=NULL){
            len++;
            p = p->next;
        }
        p = q->next;
        int j = len/2 -1;
        q->next = NULL;
        while(j){
            newHead = p->next;
            p->next = q;
            q = p;
            p = newHead;
            j--;
        }
        if(len&1){
            p = p->next;
        }
            while(q!=NULL && p!=NULL && q->val == p->val){
                q = q->next;
                p = p->next;
            }
            if(q==NULL && p==NULL)
                return true;
            else 
                return false;
        
    }
};

方法二:

/**
 * 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* p = head;
        stack<int> s;
        int len = 0;
        while(p!=NULL){
            len++;
            p = p->next;
        }
        p = head;
        int j = len/2;
        while(j){
            s.push(p->val);
            p = p->next;
            j--;
        }
        if(len&1)
            p = p->next;
        while(p!=NULL){
            if(p->val == s.top()){
                p = p->next;
                s.pop();
            }else
                return false;
        }
        return true;
    }
};

运行结果:

  方法一:执行用时 :20 ms, 在所有C++提交中击败了99.38%的用户

      内存消耗 :12.6 MB, 在所有C++提交中击败了59.98%的用户
  方法二:执行用时 :60 ms, 在所有C++提交中击败了8.86%的用户
      内存消耗 :13.2 MB, 在所有C++提交中击败了24.59%的用户

猜你喜欢

转载自www.cnblogs.com/lpomeloz/p/11022708.html
今日推荐