24. 两两交换链表中的节点
重点:虚拟头节点
别的都还挺简单的
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* curr = dummy;
while(curr->next != NULL&& curr->next->next != NULL){
ListNode* temp = curr->next->next->next;
ListNode* prev = curr->next;
ListNode* now = curr->next->next;
now->next = prev;
prev->next = temp;
curr->next = now;
curr = prev;
}
return dummy->next;
}
};
19.删除链表的倒数第N个节点
重点: 快慢指针,虚拟头节点
难点: 慢指针慢多少合适
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* fast = dummy;
ListNode* slow = dummy;
while(n >= 0 ){
fast = fast->next;
n--;
}
while(fast != NULL){
fast = fast->next;
slow = slow->next;
}
ListNode* temp = slow->next;
slow->next = slow->next->next;
delete temp;
return dummy->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* tempA = headA;
int countA = 0;
while(tempA != NULL){
countA++;
tempA = tempA->next;
}
ListNode* tempB = headB;
int countB = 0;
while(tempB != NULL){
countB++;
tempB = tempB->next;
}
int minCount = min(countA,countB);
if(minCount == countA){
int diff = countB - minCount;
while(diff > 0){
diff--;
headB = headB->next;
}
}else{
int diff = countA - minCount;
while(diff > 0){
diff--;
headA = headA->next;
}
}
while(headA != NULL){
//注意不是数值相等!!!是地址相等
if(headA == headB){
return headA;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};
142.环形链表II
重点:快慢指针
通过数学来求出快指针会在第一圈越过慢指针,以及 从head到圈开头 和 fast与slow交接的地方 到 圈开头的距离是一样的
背吧,自己想不出来
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
ListNode* inLoop = fast;
ListNode* fromHead = head;
while(inLoop != fromHead){
inLoop = inLoop->next;
fromHead = fromHead->next;
}
return fromHead;
}
}
return NULL;
}
};