206. 反转链表 - 力扣(LeetCode)https://leetcode.cn/problems/reverse-linked-list/
答案:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
while(cur)
{
struct ListNode* next = cur->next;
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
解题思路:尾插
876. 链表的中间结点 - 力扣(LeetCode)https://leetcode.cn/problems/middle-of-the-linked-list/
答案:
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* tail = head;
int count = 1;
//计算长度
while(tail->next != NULL)
{
count++;
tail = tail->next;
}
count =count/2;
struct ListNode* cur = head;
//找中点
while(count)
{
count--;
cur = cur->next;
}
return cur;
}
21. 合并两个有序链表 - 力扣(LeetCode)https://leetcode.cn/problems/merge-two-sorted-lists/
答案:
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode* tail = NULL;
while(list1 || list2)
{
//list1结束后
if(list1 == NULL)
{
while(list2)
{
struct ListNode* cur = list2->next;
list2->next = tail;
tail = list2;
list2 = cur;
}
break;
}
list2结束后
if(list2 == NULL)
{
while(list1)
{
struct ListNode* cur = list1->next;
list1->next = tail;
tail = list1;
list1 = cur;
}
break;
}
//比较大小
if(list1->val <= list2->val)
{
struct ListNode* cur = list1->next;
list1->next = tail;
tail = list1;
list1 = cur;
}
else
{
struct ListNode* cur = list2->next;
list2->next = tail;
tail = list2;
list2 = cur;
}
}
//遍历链表找头节点
struct ListNode* newhead = NULL;
while(tail)
{
struct ListNode* cur = tail->next;
tail->next = newhead;
newhead = tail;
tail = cur;
}
return newhead;
}
解题思路:
![]()
141. 环形链表 - 力扣(LeetCode)https://leetcode.cn/problems/linked-list-cycle/description/
答案:
bool hasCycle(struct ListNode *head) {
struct ListNode *slow = head;
struct ListNode *fast = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
return true;
}
}
return false;
}
解题思路:快慢指针,追击问题
之所以slow和fast相差1而不是其他是因为其他数值有可能会使fast在追slow的过程中越过slow。
142. 环形链表 II - 力扣(LeetCode)https://leetcode.cn/problems/linked-list-cycle-ii/
答案:
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
struct ListNode* meet = slow;
while(meet != head)
{
meet = meet->next;
head = head->next;
}
return meet;
}
}
return NULL;
}
解题思路:当head和meet相遇时即入口点