24. 两两交换链表中的节点:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//带数量的先看奇偶,带链表都需要判断空
ListNode* swapPairs(ListNode* head) {
ListNode* dummyNode = new ListNode(0);
dummyNode -> next= head;
ListNode* cur = dummyNode;
//注意后面容易空指针异常
while(cur -> next != NULL && cur -> next ->next != NULL){
ListNode* templ = cur ->next;
ListNode* tempr = templ ->next ->next;
cur -> next = cur -> next ->next;
cur -> next ->next = templ;
cur -> next ->next ->next = tempr;
cur = templ;
}
return dummyNode -> next;
}
};
19.删除链表的倒数第一n个结点:给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
//删除结点必须知道当前结点的上一个结点,所以n+1
//双指针思路解决倒数第n个问题
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyNode = new ListNode(0);
dummyNode ->next = head;
ListNode* fast = dummyNode;
ListNode* slow = dummyNode;
n++;
while(n-- && fast != NULL){
fast = fast -> next;
}
while(fast != NULL){
fast = fast -> next;
slow = slow -> next;
}
ListNode* temp = slow -> next;
slow->next = slow->next->next;
delete temp;
ListNode* p = dummyNode -> next;
delete dummyNode;
return p;
}
};
面试题 02.07. 链表相交:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
class Solution {
## 想出来用while和count计算两个链表的长度但是后面不好想
## 做法跟上一题目类似,用while先走到一样的长度,之后对指针进行比较(不是数值)
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* a =headA;
ListNode* b =headB;
int counta = 0;
int countb = 0;
while(a != NULL){
counta++;
a = a->next;
}
while(b != NULL){
countb++;
b = b ->next;
}
a = headA;
b = headB;
if (countb > counta){
swap(counta, countb);
swap(a, b);
}
int gap = counta - countb;
while(gap--){
a = a->next;
}
while(a != NULL){
if(a == b){ //指针比较
return a;
}
a = a->next;
b = b->next;
}
return NULL;
}
};
142. 环形链表||:
题意: 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
## 数学相关的推理证明,比较考验逻辑,学习思路。(快慢指针解法)
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast -> next != NULL){
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow){
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2){
index1 = index1 -> next;
index2 = index2 -> next;
}
return index1;
}
}
return NULL;
}
};