LC141 环形链表
注意快慢指针的使用
bool hasCycle(ListNode *head) {
if(head == nullptr) return false;
ListNode *fast = head, *slow = head;
while(fast->next && fast->next->next) {
slow = slow->next;
fast = fast->nex
if(fast == slow) return true;
}
return false;
}
LC206 反转链表
ListNode* reverseList(ListNode* head) {
ListNode *cur = head, *pre = nullptr;
while(cur) {
ListNode *tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
ListNode* reverseList(ListNode* head) {
return reverse(head, nullptr);
}
ListNode* reverse(ListNode* cur, ListNode* pre) {
if(cur == nullptr) return pre;
ListNode *tmp = cur->next;
cur->next = pre;
return reverse(tmp, cur);
}
LC234 回文链表
时间复杂度:O(n) 空间复杂度:O(1)
bool isPalindrome(ListNode* head) {
ListNode *slow = head, *fast = head, *prev = nullptr;
while(fast) {
slow = slow->next;
fast = fast->next ? fast->next->next : fast->next;
}
while(slow) {
ListNode *tmp = slow->next;
slow->next = prev;
prev = slow;
slow = tmp;
}
while(head && prev) {
if(head->val != prev->val) return false;
head = head->next;
prev = prev->next;
}
return true;
}
|