leetcode系列(16)判断链表是否为回文

来源:互联网 发布:中国移动网络测试 编辑:程序博客网 时间:2024/05/19 13:56

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?

判断一个链表的所有元素是否为回文,本身没什么难度,但是O(1)的空间复杂度就麻烦点了:将链表分裂为两个等长的链表,然后逆序其中一个,最后逐个比较两个链表的每个元素,如果全部相等就是Palindrome lsit,但是需要考虑链表长度为奇数的情况。

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 == nullptr) {            return true; // IMHO this should be false but is true in leetcode oj        }        if (head->next == nullptr) {            return true;        }        // get the len of the list        int len = 0;        for (auto ptr = head; ptr != nullptr; ptr = ptr->next) {            len++;        }        // get the header of another half of the list        int nl = len / 2;        auto ptr = head;        for (int i = 0; i != nl; ++i) {            ptr = ptr->next;        }        if (len % 2 != 0) {            ptr = ptr->next;        }        // reverse another half        ListNode* pre = nullptr;        auto cur = ptr;        while (cur != nullptr) {            auto post = cur->next;            cur->next = pre;            pre = cur;            cur = post;        }        ptr = pre;                // compare two half list        for (int i = 0; i != nl; ++i) {            if (ptr->val != head->val) {                return false;            }            ptr = ptr->next;            head = head->next;        }        return true;    }};

Python代码

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param {ListNode} head    # @return {boolean}    def isPalindrome(self, head):        l = []        while head != None:            l.append(head.val)            head = head.next        i = 0        j = len(l) - 1        while i < j:            if l[i] != l[j]:                return False            i += 1            j -= 1        return True        


0 0