● 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*dummyhead=new ListNode(0);
dummyhead->next=head;//设置一个虚拟头结点
ListNode*cur=dummyhead;//将虚拟头结点指向head,方便做后续的删除操作
while(cur->next!=nullptr&&cur->next->next){//单数节点和双数节点分别操作
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+1,要考虑具体的实现方式
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * dummyhead=new ListNode(0);
ListNode* tmp;
dummyhead->next=head;
ListNode* slow=dummyhead;
ListNode* fast=dummyhead;
while(n--&&fast!=NULL){
fast=fast->next;
}
fast=fast->next;
while(fast!=NULL){
fast=fast->next;
slow=slow->next;
}
tmp=slow->next;
slow->next=slow->next->next;
delete tmp;
return dummyhead->next;
}
};
● 面试题 02.07. 链表相交
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA=headA;
ListNode* curB=headB;
int lenA=0;
int lenB=0;
//先求出链表的长度
while(curA!=NULL){
curA=curA->next;
lenA++;
}
while(curB!=0){
curB=curB->next;
lenB++;
}
//将其中的数据重新置为头结点
curA=headA;
curB=headB;
if(lenB>lenA){
swap(lenB,lenA);
swap(curA,curB);
}
int gap=lenA-lenB;
while(gap--){
curA=curA->next;
}
while(curA!=NULL){
if(curA==curB)
{
return curA;
}
curA=curA->next;
curB=curB->next;
}
return NULL;
}
};
● 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(fast==slow){
ListNode* index1=fast;
ListNode* index2=head;
while(index1!=index2){
index1=index1->next;
index2=index2->next;
}
return index2;
}
}
return NULL;
}
};