/**
* 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) {
if(head==nullptr||head->next==nullptr){
return head;
}
ListNode* dummy=new ListNode(0);
dummy->next=head;
ListNode* prev=dummy;
ListNode* cur=head;
while(cur!=nullptr&&cur->next!=nullptr){
ListNode* next=cur->next;
cur->next=next->next;
next->next=cur;
prev->next=next;
prev=cur;
cur=cur->next;
}
return dummy->next;
}
};
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
/**
* 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* removeNthFromEnd(ListNode* head, int n) {
ListNode* tmp=head;
int count=0;
while(tmp!=nullptr){
count++;
tmp=tmp->next;
}
ListNode* dummy=new ListNode(0);
dummy->next=head;
if(count==1){
head=nullptr;
return head;
}else{
ListNode* cur=dummy;
for(int i=1;i<=count-n;i++){
cur=cur->next;
}
cur->next=cur->next->next;
ListNode* ans=dummy->next;
delete dummy;
return ans;
}
}
};
面试题 02.07. 链表相交 - 力扣(LeetCode)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getCount(ListNode* L){
int count=0;
ListNode* current = L; //使用 current 指针迭代链表
while(current!=nullptr){
count++;
current=current->next;
}
return count;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL||headB==NULL){
return nullptr;
}
ListNode* pA=headA;
ListNode* pB=headB;
int countA = getCount(pA);
int countB = getCount(pB);
pA=headA;
pB=headB;
// 先将较长的链表指针移动到与较短链表相同长度的位置
if(countA<=countB){
for(int i=0;i<countB-countA;i++){
pB=pB->next;
}
}else{
for(int i=0;i<countA-countB;i++){
pA=pA->next;
}
}
// 遍历链表,找到相交的节点
while(pA!=nullptr && pB!=nullptr && pA!=pB){
pA = pA->next;
pB = pB->next;
}
return pA; // 返回相交的节点,即使没有相交也会返回 null
}
};
/**
* 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* slow=head;
ListNode* fast=head;
while(fast!=nullptr){
slow=slow->next;
if(fast->next==nullptr){
return nullptr;
}
fast=fast->next->next;
if(fast==slow){
ListNode* tmp=head;
//第二次相遇
while(tmp!=slow){
tmp=tmp->next;
slow=slow->next;
}
return tmp;
}
}
return NULL;
}
};