24. 两两交换链表中的节点
画图!!!链表这一点要画图,画图很好理解,之后注意一下循环的条件!
代码如下:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* cur=dummyhead;
while(cur->next!=nullptr&&cur->next->next!=nullptr){
ListNode* tmp=cur->next;
ListNode* tmp1=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next=tmp;
cur->next->next->next=tmp1;
cur=cur->next->next;
}
return dummyhead->next;
}
};
19.删除链表的倒数第N个节点
利用双指针!!又是双指针,就是把两个指针先空出n个位置,之后在一起移动,因为前面指针要指导到删除的元素前一个,所以后面的指针还要多移一步。
代码如下:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead= new ListNode(0);
dummyhead->next=head;
ListNode* low=dummyhead;
ListNode* high=dummyhead;
while(n--&&high!=nullptr)
high=high->next;
high=high->next;
while(high!=nullptr){
high=high->next;
low=low->next;
}
low->next=low->next->next;
return dummyhead->next;
}
};
面试题 02.07. 链表相交
106链表相交:前提是所有链表结构里不存在环,所以看是否相交,只需要将在最长的链表遍历短链表那个距离。
代码如下
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead= new ListNode(0);
dummyhead->next=head;
ListNode* low=dummyhead;
ListNode* high=dummyhead;
while(n--&&high!=nullptr)
high=high->next;
high=high->next;
while(high!=nullptr){
high=high->next;
low=low->next;
}
low->next=low->next->next;
return dummyhead->next;
}
};
142.环形链表II
利用两个指针,一块一慢,他们一定会在环里相遇,之后利用数学公式推导出一些结论,还得看一遍视频才能理解透彻。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
while(fast!= NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast) {//如果相遇
ListNode* index1=fast;
ListNode* index2=head;
while(index1!=index2){
index1=index1->next;
index2=index2->next;
}
return index2;
}
}
return NULL;
}
};
总结
两个指针的应用很重要,在链表中可以找到倒数元素以及判读是否有环等!!注意双指针的思想!