1. 24. 两两交换链表中的节点(后续重做)
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移动两位,准备下一轮交换
}
ListNode* result = dummyHead->next;
delete dummyHead;
return result;
}
};
2. 19.删除链表的倒数第N个节点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode stLNRes;
stLNRes.next = head;
while(n--)
{
if(head != NULL)
{
head = head->next;
}
else
{
return stLNRes.next;
}
}
ListNode *stLKSlow = &stLNRes;
while(head)
{
head = head->next;
//因为开始申请的是一个虚拟节点,所以此处next才是要找的值
stLKSlow = stLKSlow->next;
}
stLKSlow->next = stLKSlow->next->next;
return stLNRes.next;
}
};
3. 面试题 02.07. 链表相交
思路比较清晰明了
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *headATmp = headA;
ListNode *headBTmp = headB;
int iLenA = 0;
int iLenB = 0;
while(headATmp != NULL)
{
iLenA++;
headATmp = headATmp->next;
}
while(headBTmp != NULL)
{
iLenB++;
headBTmp = headBTmp->next;
}
int iLenDiff = 0;
ListNode *stLKFast;
ListNode *stLKSlow;
if(iLenA > iLenB)
{
iLenDiff = iLenA - iLenB;
stLKFast = headA;
stLKSlow = headB;
}
else
{
iLenDiff = iLenB - iLenA;
stLKFast = headB;
stLKSlow = headA;
}
while(iLenDiff--)
{
stLKFast = stLKFast->next;
}
while(stLKFast != NULL && stLKSlow != NULL)
{
if(stLKFast == stLKSlow)
{
return stLKFast;
}
stLKFast = stLKFast->next;
stLKSlow = stLKSlow->next;
}
return NULL;
}
};
4. 环形链表II
注意数学解释(后续在此补充说明)
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *stLKSlow = head;
ListNode *stLKFast = head;
//注意此处是判断FAST是否为空!!!
while(stLKFast != NULL &&stLKFast->next != NULL)
{
stLKSlow = stLKSlow->next;
stLKFast = stLKFast->next->next;
if(stLKFast == stLKSlow)
{
ListNode *stLKIndex1 = stLKFast;
ListNode *stLKIndex2 = head;
while(stLKIndex1 != stLKIndex2)
{
stLKIndex1 = stLKIndex1->next;
stLKIndex2 = stLKIndex2->next;
}
return stLKIndex1;
}
}
return NULL;
}
};