代码随想录刷题第四天
两两交换链表中的节点
#include<iostream>
using namespace std;
// struct ListNode
// {
// int val;
// ListNode *next;
// ListNode(int val): val(0),next(nullptr){}
// };
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 * tmp1, *tmp2;
tmp1 = cur->next->next->next;
tmp2 = cur->next;
cur->next = cur->next->next;
cur->next->next = tmp2;
cur->next->next->next = tmp1;
cur = cur->next->next;
}
return dummyhead->next;
}
};
循环不变量,一直按照一个规则处理,一次移动两位即可
删除链表的倒数第 N 个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// if (head = nullptr)
// {
// }
ListNode *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *fast = dummyhead,*slow = dummyhead;
while (n--)
{
fast = fast->next;
}
while (fast->next != nullptr)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};
双指针的链表应用,这个题目不需要判断链表为空的情况
##面试题 02.07. 链表相交 - 力扣(LeetCode)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode * curA = headA;
ListNode *curB = headB;
int sizeA = 0, sizeB=0;
int result;
bool flag = 0;
while(curA){
curA = curA->next;
sizeA++;
}
while(curB){
curB = curB->next;
sizeB++;
}
int dif = sizeA - sizeB;
curA = headA;
curB = headB;
if(dif == 0){
if(curA == curB){
return curB;
}
}
if(dif > 0){
//sizea big
while(dif--){
curA = curA->next;
}
flag = 1;
}
if(dif < 0){
//sizea big
if(flag == 1){
dif++;
flag = 0;
}
dif = -dif;
while(dif--){
curB = curB->next;
}
}
while(curA){
if(curB == curA){
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
博主给的是用swap交换,这样可以大大简化运算,不需要额外的开销,比较方便。我这种方法由于判断条件过多,可能在某种情况下影响时间复杂度
142. 环形链表 II - 力扣(LeetCode)
/**
* 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){
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;
}
};
注意逻辑,要在一个条件成立的情况下,来判断第二个循环是否相等
324

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



