Day4 :
24. 两两交换链表中的节点
注意需要画图进行操作,其次要链表的奇数和偶数这里主要是循环终止条件的问题,空指针操作异常以及边界的处理问题。
这里我觉得代码随想录将代码讲解得非常详细:每一步分解的非常得简单易懂,所以我们只需要解决了边界条件之后得话同时多几个变量将几个链表打乱之后找不到得链表结点首先进行保存下来后面就好操作。
class Solution
{
class ListNode
{
public:
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){}
}
ListNode* swapPairs(LiseNode* head)
{
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
cur = dummyhead;
while(cur->next&& cur->next->next)
{
//因为打乱链表顺序得原因:所以需要保存打乱链表顺序后找不到得链表结点
ListNode* temp = cur->next;
ListNode* temp1= cur->next->next->next;
cur->next = cur->next->next;
temp->next = temp->next->next;
cur->next->next = temp;
cur = cur->next->next
}
}
};
19.删除链表的倒数第N个节点
本题目很简单只需要明白快慢指针的思想:让快指针先走n+1步,然后让快慢指针同时步进,当快指针到达最后结点得同时,慢指针的则到达了要删除目标结点得前一个结点。明白这个思想这个问题就变得非常简单;
/**
* 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* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
n++;
while(n--)
{
fast = fast->next;
}
while(fast)
{
slow = slow->next;
fast = fast->next;
}
slow->next=slow->next->next;
return dummyhead->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) { // 求链表A的长度
lenA++;
curA = curA->next;
}
while (curB != NULL) { // 求链表B的长度
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
142. 环形链表 II
这道题还没有搞懂明天继续解决先给出录哥得代码
/**
* 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 != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
// 快慢指针相遇,此时从head 和 相遇点,同时查找直至相遇
if (slow == fast) {
ListNode* index1 = fast;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2; // 返回环的入口
}
}
return NULL;
}
};