24. 两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next != nullptr && cur->next->next !=nullptr){
ListNode* tmp = cur->next;
ListNode* tmp_1 = cur->next->next->next;
cur->next =cur->next->next;
cur->next->next = tmp;
cur->next->next->next = tmp_1;
cur = cur->next->next;
}
return dummyHead->next;
}
};
跟着交换步骤一步一步来,注意交换过程中指针改变了,用临时节点存储之前的指针。
19.删除链表的倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
快慢指针
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;
while(n-- && fast->next !=nullptr){
fast = fast->next;
}
fast = fast->next;
while( fast != NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
面试题 02.07. 链表相交
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while(curA != NULL){
curA = curA->next;
lenA++;
}
while(curB != NULL){
curB = curB->next;
lenB++;
}
curA = headA;
curB = headB;
if(lenB > lenA){
swap(lenA,lenB);
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
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 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* index_1 = fast;
ListNode* index_2 = head;
while(index_1 != index_2){
index_1 = index_1->next;
index_2 = index_2->next;
}
return index_1;
}
}
return NULL;
}
};
5272

被折叠的 条评论
为什么被折叠?



