LeetCode

来源:互联网 发布:苹果8没网络 编辑:程序博客网 时间:2024/06/08 00:07


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(n),至于空间复杂度,我觉得翻转一个链表的空间复杂度是O(n),不是O(1)

/** * 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) return true;        ListNode* tail = head;        int len = 0;        while (tail) {            len++;            tail = tail->next;        }        tail = NULL;        ListNode* cur = NULL;        int len2 = len / 2;        while(len2--) {            tail = head->next;            head->next = cur;            cur = head;            head = tail;        }        if (len % 2) head = head->next;        bool flag = false;        while (head) {            if (head->val == cur->val) {                head = head->next;                cur = cur->next;                continue;            }            flag = true;            break;        }        if (flag) return false;        return true;    }};

原创粉丝点击