LeetCode24
本人代码:(对头节点单独处理)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* _head= new ListNode(0);
_head->next=head;
if(head==NULL||head->next==NULL) return head;
ListNode* fast=head->next;
ListNode* low=head;
ListNode* tmp=_head;
int n=0;
while(low->next!=NULL||tmp->next!=NULL)
{
n++;
low->next=fast->next;
fast->next=low;
tmp->next=fast;
tmp=fast->next;
low=tmp->next;
if(tmp->next==NULL||low->next==NULL)break;
fast=low->next;
}
return _head->next;
}
};
答案代码;
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
dummyHead->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
ListNode* cur = dummyHead;
while(cur->next != nullptr && cur->next->next != nullptr) {
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; // cur移动两位,准备下一轮交换
}
return dummyHead->next;
}
};
感悟:
- 经常需要单独处理头结点,还是需要了解如何不会导致头结点错误。
LeetCode19
本人解法: (使用快慢指针,王道提到过得方法)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* _head=new ListNode(0);
_head->next=head;
ListNode* tmp=_head;
ListNode* deletel =_head;
while(n--)
{
tmp=tmp->next;
}
while(tmp->next!=NULL)
{
deletel=deletel->next;
tmp=tmp->next;
}
ListNode* tmp1=deletel->next;
deletel->next=tmp1->next;
tmp1->next=NULL;
delete(tmp1);
return _head->next;
}
};
感悟:
王道数据结构yyds!
面试02.07
题目:
本人解法:(保证两个节点指针剩下的节点个数保持一致)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int A=0,B=0;
ListNode* curA=headA;
ListNode* curB=headB;
if(headA==NULL||headB==NULL) return NULL;
while(curA->next!=NULL)
{
A++;
curA=curA->next;
}
while(curB->next!=NULL)
{
B++;
curB=curB->next;
}
curA=headA;
curB=headB;
if(A>=B)
{
int AB=A-B;
while(AB--)
{
curA=curA->next;
}
}
else
{
int BA=B-A;
while(BA--)
{
curB=curB->next;
}
}
while(curA!=curB&&curA!=NULL&&curB!=NULL){
curA=curA->next;
curB=curB->next;
}
if(curA==NULL||curB==NULL) return NULL;
return curA;
}
};
感悟:
- 王道继续yyds!
- 每道题都需要考虑头指针为空的情况
LeetCode142
标准解法:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* low = head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
low=low->next;
if(low==fast)
{
ListNode *index1 = fast;
ListNode *index2 = head;
while(index1!=index2)
{
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return NULL;
}
};
感悟:
- 王道应该讲过,我不记得了
- 需要动手列公式,找到相关性才能找到相遇节点和环入口