24. 两两交换链表中的节点
/** @lc app=leetcode.cn id=142 lang=cpp** [142] 环形链表 II*/// @lc code=start
/*** 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!=nullptr&&fast->next!=nullptr){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;}
};
// @lc code=end
19.删除链表的倒数第N个节点
/** @lc app=leetcode.cn id=19 lang=cpp** [19] 删除链表的倒数第 N 个结点*/// @lc code=start
/*** 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* dhead=new ListNode(0);dhead->next=head;ListNode* slow=dhead;ListNode* fast=dhead;while(n--&&fast!=nullptr){fast=fast->next;}fast=fast->next;while(fast!=nullptr){fast=fast->next;slow=slow->next;}slow->next=slow->next->next;return dhead->next;}
};
// @lc code=end
面试题 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,lenb=0;while(curA!=nullptr){lena++;curA=curA->next;}while(curB!=nullptr){lenb++;curB=curB->next;}curA=headA;curB=headB;if(lenb>lena){swap(lena,lenb);swap(curA,curB);}int gap=lena-lenb;while(gap--){curA=curA->next;}while (curA!=nullptr){if(curA==curB)return curA;curA=curA->next;curB=curB->next;}return NULL;}
};
142.环形链表II
/** @lc app=leetcode.cn id=142 lang=cpp** [142] 环形链表 II*/// @lc code=start
/*** 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!=nullptr&&fast->next!=nullptr){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;}
};
// @lc code=end
链表题一定要多画图模拟过程