目录
状态:已AC,要设两个临时节点temp、temp1,不然指针指向错误,同时画图也很重要
- class Solution {
- public:
- ListNode* swapPairs(ListNode* head) {
- ListNode* dummyHead = new ListNode(0);
- dummyHead->next = head;
- ListNode* cur = dummyHead;
- while(cur->next!=NULL&&cur->next->next!=NULL)
- {
- ListNode*temp=cur->next;
- ListNode*temp1=cur->next->next->next;
- cur->next=cur->next->next;
- cur->next->next=temp;
- cur->next->next->next=temp1;
- cur=cur->next->next;
- }
- return dummyHead->next;
- }
- };
状态:看完思路AC,注意fast指针走n+1步,以保证slow能走到想要的节点的前一个节点
定义fast指针和slow指针,初始值为虚拟头结点
fast首先走n + 1步 ,这样同时移动slow的时候才能指向删除节点的上一个节点(方便做删除操作)
fast和slow同时移动,直到fast指向末尾
删除slow指向的下一个节点
- class Solution {
- public:
- ListNode* removeNthFromEnd(ListNode* head, int n) {
- ListNode* dummyHead = new ListNode(0);
- dummyHead->next = head;
- ListNode* slow = dummyHead;
- ListNode* fast = dummyHead;
- while(n-- && fast != NULL) {
- fast = fast->next;
- }
- fast = fast->next;
- while (fast != NULL) {
- fast = fast->next;
- slow = slow->next;
- }
- slow->next = slow->next->next;
- return dummyHead->next;
- }
- };
状态:已AC,注意不是数一样就行,而是指针一致
- class Solution {
- public:
- ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
- ListNode* curA=headA;
- ListNode* curB=headB;
- int lenA=0,lenB=0;
- while(curA!=NULL)
- {
- lenA++;
- curA=curA->next;
- }
- while(curB!=NULL)
- {
- lenB++;
- curB=curB->next;
- }
- curA=headA;
- curB=headB;
- if (lenB > lenA) {// 让curA为最长链表的头,lenA为其长度
- swap (lenA, lenB);
- swap (curA, curB);
- }
- int gap=lenA-lenB;
- while(gap--)
- {
- curA=curA->next;
- }
- while(curA!=NULL)
- {
- if(curA==curB)
- {
- return curA;
- }
- curA=curA->next;
- curB=curB->next;
- }
- return NULL;
- }
- };
状态:思路还需梳理,有一些数学推导容易考虑不到
1)使用快慢指针法,分别定义 fast 和 slow 指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环
2)判断环入口
p.s为什么slow指针是
,不是
(如图)
从头结点出发一个指针,从相遇节点 也出发一个指针,这两个指针每次只走一个节点, 那么当这两个指针相遇的时候就是 环形入口的节点
- class Solution {
- public:
- 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;
- }
- };