链表:实践环形链表(142,两种方法)及反转一个单链表(206)。
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Note: Do not modify the linked list.
一。思想:从头遍历,如果它已经被访问,说明它是环的开始结点,就返回,如果整个链表都没有都没有已访问的结点,就返回NULL。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//创建visited的map,键为ListNode*类型的指针,值为是否访问
map<ListNode*, bool> visited;
//直到没有后继结点为止
while(head != NULL)
{
//如果已经被访问了,说明有环,而且这个结点是环的开始结点,返回它
if(visited[head] == true)
return head;
//如果没有被访问,就使之被访问
visited[head] = true;
//指向下一个结点
head = head->next;
}
return NULL;
}
};
二。思想:使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head) return NULL;
struct ListNode *fast = head;
struct ListNode *slow = head;
while(fast!=NULL&&fast->next!=NULL) {
fast = fast->next->next;
slow = slow->next;
if(fast==slow)
break;
}
if(fast==slow&&fast->next!=NULL) {
slow = head;
while(slow!=fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
return NULL;
}
};
三。迭代方法(来自参考资料2)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) //链表为空或者仅1个数直接返回
return head;
//创建两个指针,一个指向头结点,一个指向null
ListNode* p = head, *newH = NULL;
//一直迭代到链尾
while (p != NULL)
{
//暂存p下一个地址,防止变化指针丢失后面数的地址
ListNode* tmp = p->next;
//p->next指向前一个空间
p->next = newH;
//新链表的头移动到p,扩长一步链表
newH = p;
//p指向原始链表p指向的下一个空间
p = tmp;
}
return newH;
}
};
206. Reverse Linked List
Reverse a singly linked list.
Example:
完整代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//如果head为NULL或者下一个结点为NULL,就返回NULL
if(head == NULL||head->next == NULL){
return head;
}
ListNode *ans = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return ans;
}
};
参考资料: