第一版:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* pre = head,*p = head->next;
ListNode* ppre = NULL;
head = p;
while(p!=NULL)
{
pre->next = p->next;
p->next = pre;
if(ppre) ppre->next = p;
ppre = pre;
pre= pre->next;
if(!pre) break;
p = pre->next;
}
return head;
}
也可以设置虚拟结点来做该题
第二版(递归法,使用递归前提看看操作是否重复执行)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* p = head->next;
head->next = swapPairs(p->next);
p->next = head;
return p;
}
};
第一版:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* Head = new ListNode(0);
Head->next = head;
ListNode* slow=Head,*fast=Head;
while(n--&&fast!=NULL) fast = fast->next;
while(fast->next!=NULL)
{
slow = slow->next;
fast = fast->next;
}
ListNode* del = slow->next;
slow->next = del->next;
delete del;
return Head->next;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while (curA != NULL) { // 求链表A的长度
lenA++;
curA = curA->next;
}
while (curB != NULL) { // 求链表B的长度
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
整体思路:找环的入口需要一些公式推导,先证明有环,即快慢指针,一个走两步一个走一步,在有环的基础上, 快慢指针相遇的时候,距离是 short*2 = fast,具体公式推导代码代码随想录有,
总之,由最终理论可得:从head结点出发,从快慢指针相遇结点出发,两者相遇后就是环的入口地址
第一版:(还可优化)
ListNode *detectCycle(ListNode *head) {
if (!head) return NULL;
ListNode* slow=head,*fast=head;
//相遇退出来或无环退出来
while(fast!=NULL)
{
if(!fast->next) break;
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
if (!fast||!fast->next) return NULL;
ListNode *p = head;
while(p)
{
if(p==slow) break;
p=p->next;
slow=slow->next;
}
return p;
}
参考版:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
// 快慢指针相遇,此时从head 和 相遇点,同时查找直至相遇
if (slow == fast) {
ListNode* index1 = fast;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2; // 返回环的入口
}
}
return NULL;
}