一开始没有设置虚拟头节点,会导致找不到head
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy=new ListNode(0);
dummy->next=head;
if (head==nullptr)
return head;
ListNode *cur=dummy;
//ListNode *tmp1=cur->next;
//ListNode *tmp2=cur->next->next->next;
while(cur->next!=nullptr&&cur->next->next!=nullptr)
{
ListNode *tmp1=cur->next;
ListNode *tmp2=cur->next->next->next;
cur->next=tmp1->next;
tmp1->next->next=tmp1;
tmp1->next=tmp2;
cur=tmp1;
//tmp1=cur->next;
//tmp2=cur->next->next->next;
}
return dummy->next;
}
}
19. 删除链表的倒数第 N 个结点 - 力扣(Leetcode)
刷过,双指针,右边先移动n
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy=new ListNode(0);
dummy->next=head;
ListNode *right=dummy;
ListNode *left=dummy;
while(n--)
{
right=right->next;
}
while(right->next!=nullptr)
{
right=right->next;
left=left->next;
}
left->next=left->next->next;
return dummy->next;
}
};
看了一下思路,while循环的判断依据写成了curA->next!=nullptr,导致在链表仅有一个数据的时候会出错
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *curA=headA;
ListNode *curB=headB;
int sizeA=0;
int sizeB=0;
while(curA!=nullptr)
{
curA=curA->next;
sizeA++;
}
while(curB!=nullptr)
{
curB=curB->next;
sizeB++;
}
curA=headA;
curB=headB;
int size=0;
size=(sizeA>sizeB)?(sizeA-sizeB):(sizeB-sizeA);
if(sizeA>sizeB)
{
while(size--)
curA=curA->next;
}
else
{
while(size--)
curB=curB->next;
}
while(curA!=nullptr)
{
if(curA==curB)
return curA;
else
{
curA=curA->next;
curB=curB->next;
}
}
return nullptr;
}
};
环形链表还是需要再看一下,涉及到一些数学思维
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode*fast=head;
ListNode*slow=head;
while(fast!=nullptr&&fast->next!=nullptr)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
ListNode*index1=head;
ListNode*index2=slow;
while(index1!=index2)
{
index1=index1->next;
index2=index2->next;
}
return index1;
}
}
return nullptr;
}
};