代码随想录Day4 | 链表part2

本文介绍了如何使用双指针技巧解决链表问题,包括两两交换链表节点、删除链表的倒数第N个节点,以及检测环形链表。这些方法强调了双指针在链表操作中的重要性。
摘要由CSDN通过智能技术生成

24. 两两交换链表中的节点

画图!!!链表这一点要画图,画图很好理解,之后注意一下循环的条件!

代码如下:
 

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyhead=new ListNode(0);
        dummyhead->next=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;
        }
        return dummyhead->next;


        
    }
};

19.删除链表的倒数第N个节点 

利用双指针!!又是双指针,就是把两个指针先空出n个位置,之后在一起移动,因为前面指针要指导到删除的元素前一个,所以后面的指针还要多移一步。
代码如下:
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummyhead= new ListNode(0);
        dummyhead->next=head;
        ListNode* low=dummyhead;
        ListNode* high=dummyhead;
        while(n--&&high!=nullptr)
            high=high->next;
        high=high->next;
        while(high!=nullptr){
            high=high->next;
            low=low->next;
        }
        low->next=low->next->next;
    return dummyhead->next;

    }
};

面试题 02.07. 链表相交

106链表相交:前提是所有链表结构里不存在环,所以看是否相交,只需要将在最长的链表遍历短链表那个距离。

代码如下

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummyhead= new ListNode(0);
        dummyhead->next=head;
        ListNode* low=dummyhead;
        ListNode* high=dummyhead;
        while(n--&&high!=nullptr)
            high=high->next;
        high=high->next;
        while(high!=nullptr){
            high=high->next;
            low=low->next;
        }
        low->next=low->next->next;
    return dummyhead->next;

    }
};

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;
        while(fast!= NULL&&fast->next!=NULL){
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast) {//如果相遇
                ListNode* index1=fast;
                ListNode* index2=head;
                while(index1!=index2){
                    index1=index1->next;
                    index2=index2->next;
                }
                return index2;
            }
        }
        return NULL;
        
    }
};

总结

两个指针的应用很重要,在链表中可以找到倒数元素以及判读是否有环等!!注意双指针的思想!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值