Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
ListNode *detectCycle(ListNode *head) {
if (head == NULL) return NULL;
ListNode* ptr = head;
ListNode* fastPtr = ptr;
do {
if (fastPtr == NULL || fastPtr->next == NULL)
return NULL;
ptr = ptr -> next;
fastPtr = fastPtr -> next -> next;
} while (ptr != fastPtr);
ptr = head;
while (ptr != fastPtr){
ptr = ptr -> next;
fastPtr = fastPtr -> next;
}
return ptr;
}
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
1. 先找出list的长度,然后找到断开处的指针。
2. 使用快慢指针的话并不能减少指针移动的操作,所以不用了
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL) return NULL;
int len = 1;
ListNode* ptr = head;
while (ptr -> next != NULL){
ptr = ptr -> next;
len++;
}
ListNode* tail = ptr;
k = k % len;
if (k == 0) return head;
ptr = head;
for (int i = 1; i < len - k; i++){
ptr = ptr -> next;
}
ListNode* newH = ptr -> next;
ptr -> next = NULL;
tail -> next = head;
return newH;
}

本文介绍了如何在链表中检测循环的起始节点及实现链表的旋转操作。通过两个核心函数,detectCycle 和 rotateRight,分别解决了链表循环检测和链表旋转的问题。detectCycle 函数使用快慢指针技巧定位循环开始节点;rotateRight 则通过计算链表长度和确定断开位置来完成链表的旋转。

被折叠的 条评论
为什么被折叠?



