Palindrome Linked List
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?
解法一:
一次遍历,装入vector,然后再一次遍历判断回文。
时间复杂度O(n),空间复杂度O(n)
/** * 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) { vector<int> v; while(head) { v.push_back(head->val); head = head->next; } for(int i = 0, j = v.size()-1; i < j; i ++, j --) { if(v[i] != v[j]) return false; } return true; } };
解法二:
找到链表中点,拆分后,逆转后半个链表,然后两个链表同时顺序遍历一次。
若链表长度为奇数,最末尾的元素可以忽略。
时间复杂度O(n),空间复杂度O(1)
时间: 2024-08-06 10:00:19