24. 两两交换链表中的节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* pre = head;
if(head == NULL )
{
return head;
}
ListNode* cur = head->next;
ListNode* virhead = new ListNode(0);
virhead -> next = head;
ListNode * p = virhead;
while(pre!= NULL && cur != NULL)
{
ListNode * temp = cur -> next;//暂时记录下一个遍历
cur -> next = pre;
pre -> next = temp;
p -> next = cur;
p = pre;
pre = temp;
if(temp != NULL)
{
cur = temp -> next;
}
}
return virhead -> next;
}
};
类似反转链表的双指针法,其实找对逻辑很简单
19. 删除链表的倒数第 N 个结点
又是双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * left = new ListNode(0);
left -> next = head;
ListNode * virhead = left;
ListNode * right = left;
int flag = 0;
while(right -> next)
{
if( flag < n)
{
right = right -> next;
flag++;
}
else
{
left = left -> next;
right = right -> next;
}
}
ListNode * cur = new ListNode(0);
cur = left -> next;
left -> next = (left -> next) -> next;
return virhead -> next;
}
};
面试题 02.07. 链表相交
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode * curA = headA;
ListNode * curB = headB;
int lenA = 0, lenB = 0;
while(curA)
{
lenA++;
curA = curA -> next;
}
while(curB)
{
lenB++;
curB = curB -> next;
}
curA = headA;
curB = headB;
if(lenA > lenB)
{
for (int i = 0 ; i < (lenA - lenB) ; i++ )//这一步复制的时候忘记调整lenA-lenB了,以后少复制
{
curA = curA -> next;
}
}
else if(lenA < lenB)
{
for (int i = 0 ; i < (lenB - lenA) ; i++ )
{
curB = curB -> next;
}
}
int len = min (lenA , lenB);
while(curA != curB && curB!= NULL)
{
curA = curA ->next;
curB = curB ->next;
}
return curA;
}
};
29行复制的时候忘记调整lenA-lenB了,以后少复制,尽量一字一字地打
142. 环形链表 II
/**
* 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;
if(head == NULL || head -> next == NULL ||(head -> next) -> next == NULL)
{
return NULL;
}
while(fast -> next != NULL && (fast -> next) -> next != NULL )
{
fast = (fast -> next) -> next;
slow = slow -> next;
if(fast == slow)
{
break;
}
}
if(fast != slow) return NULL;
ListNode * sta = head;
int len = 0;
while(sta != fast)
{
len++;
sta = sta -> next;
fast = fast -> next ;
}
return sta;
}
};
先是快指针追慢指针的追及问题,后是追及问题距离相等,不知道快慢指针有没有其他用处