24. 两两交换链表中的节点
题目: 24. 两两交换链表中的节点
文章: 24. 两两交换链表中的节点
视频: 24. 两两交换链表中的节点
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = dummy;
while(cur->next!=nullptr && cur->next->next != nullptr)
{
ListNode* temp = cur->next->next->next;
ListNode* temp1 = cur->next;
cur->next = cur->next->next;
cur->next->next = temp1;
cur->next->next->next = temp;
cur = cur->next->next;
}
return dummy->next;
}
19.删除链表的倒数第N个节点
题目: 19.删除链表的倒数第N个节点
文章: 19.删除链表的倒数第N个节点
视频: 19.删除链表的倒数第N个节点
思路
自己没想到,但是看了代码随想录感觉哪个想法很妙,倒数第N个,那么只需要保持两个数据之间间隔n只需要两个指向就可以
代码
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* fast = dummy;
ListNode* slow = dummy;
while(n>0)
{
n--;
fast = fast->next;
}
while(fast->next != nullptr)
{
fast=fast->next;
slow=slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
面试题 02.07. 链表相交
题目: 面试题 02.07. 链表相交
文章: 面试题 02.07. 链表相交
视频: 面试题 02.07. 链表相交
思路
- 相等是指针相等
- 需要末尾对其以后才能讨论相等
- 写代码看完思路才会写,愁
代码
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL||headB==NULL)
{
return NULL;
}
int A_len = 0, B_len = 0;
ListNode* A_num = headA;
ListNode* B_num = headB;
while(A_num->next != NULL)
{
A_num = A_num->next;
A_len++;
}
while(B_num->next != NULL)
{
B_num = B_num->next;
B_len++;
}
ListNode* A_cur = headA;
ListNode* B_cur = headB;
if(A_len > B_len)
{
int n = A_len - B_len;
while(n>0)
{
n--;
A_cur=A_cur->next;
}
while(A_cur != B_cur)
{
A_cur = A_cur->next;
B_cur = B_cur->next;
}
}
else
{
int n = B_len - A_len;
while(n>0)
{
n--;
B_cur=B_cur->next;
}
while(A_cur != B_cur)
{
A_cur = A_cur->next;
B_cur = B_cur->next;
}
}
return A_cur;
}
142.环形链表II
题目: 142.环形链表II
文章: 142.环形链表II
视频: 142.环形链表II
思路
*问题不知道哪里有问题。
代码
ListNode *detectCycle(ListNode *head) {
ListNode* cur=head;
ListNode* fast=head;
ListNode* slow=head;
if(fast->next==NULL || fast->next->next == NULL) return NULL;
while(slow != fast && fast!=NULL && fast->next != NULL)
{
fast=fast->next->next;
slow = slow->next;
}
ListNode* temp = fast;
while(temp !=cur)
{
temp=temp->next;
cur=cur->next;
}
return cur;
}