链表(二)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dhead = new ListNode(0);
dhead->next = head;
ListNode* cur = dhead;
while(cur->next!=nullptr && cur->next->next!=nullptr){
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
cur= cur->next->next;
}
return dhead->next;
}
};
习惯使用虚拟头节点的方法很方便的,之后就按部就班地分析,把过程用代码复现就行。
关键是想好判断遍历地条件,奇数和偶数对应的判断条件。
19.删除链表的倒数第N个节点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dhead = new ListNode(0);
dhead->next = head;
ListNode* fast = dhead;
ListNode* slow = dhead;
n++;
while(n--&& fast!=nullptr){
fast = fast->next;
}
while(fast!=nullptr){
fast = fast->next;
slow = slow->next;
}
//slow->next = slow->next->next;
ListNode* temp = slow->next;
slow->next = temp->next;
delete temp;
return dhead->next;
}
};
巧妙的设计,构成双指针进行筛选,倒数几个可以换算为相差几个,这个思路非常好。
面试题 02.07. 链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lena=0,lenb=0;
while(curA!=NULL){
lena++;
curA = curA->next;
}
while(curB!=NULL){
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(lenb--){
if(curA==curB){
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
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;
}
};
环形链表的双指针判断,要义:
- 在慢指针进入环内的第一圈就会相遇;
- 快指针的速度两倍于慢指针;
- 以相遇的位置作为指示点,指示点到环入口的"距离"与链表头节点到环入口的距离相等。