24.两两交换链表
题目链接:24. 两两交换链表中的节点 - 力扣(LeetCode)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next != NULL && cur->next->next != NULL){
ListNode* tmp = cur->next;
ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
cur->next->next->next = tmp1;
cur = cur->next->next;
}
ListNode* result = dummyHead->next;
delete dummyHead;
return result;
}
};
19.删除链表中倒数第N个节点
题目链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int size=0;
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next != NULL){
cur = cur->next;
size++;
}
int loop = size - n;
cur = dummyHead;
while (loop--){
cur=cur->next;
}
ListNode* tmp = cur->next;
cur->next = cur->next->next;
return dummyHead->next;
}
};
这个我的思路是先数有多少个节点,然后把节点减去倒着数的个数就是正着数的个数,硬给他弄成正着删
//双指针解法
/*
* 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 != NULL){
fast = fast->next;
}
while (fast != NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
这里因为n如果大于链表长度的话fast在第一个循环遍历结束后会等于空,这个时候fast->next会空指针引用,所以直接先n++比较保险,就不用引用fast指针了。
02.07.链表相交
题目链接:面试题 02.07. 链表相交 - 力扣(LeetCode)
/**
* 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* A = headA;
ListNode* B = headB;
int lengthA = 0, lengthB = 0;
while (A != NULL) {
A = A->next;
lengthA++;
}
while (B != NULL) {
B = B->next;
lengthB++;
}
A = headA;
B = headB;
if (lengthB > lengthA) {
swap(lengthA, lengthB);
swap(A, B);
}
int n = lengthA - lengthB;
while (n--) {
A = A->next;
}
while (A != NULL) {
if(A == B) return A;
A = A->next;
B = B->next;
}
return NULL;
}
};
142.环形链表
题目链接:142. 环形链表 II - 力扣(LeetCode)
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 (slow == fast) {
ListNode* cur1 = fast;
ListNode* cur2 = head;
while (cur1 != cur2) {
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
}
return NULL;
}
};
链表相关题目解题思路及链接

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



