【数据结构初阶】单链表经典算法题十道(详解+图例)—得道飞升(终篇)

hi !

目录

[9、 环形链表 ||](#9、 环形链表 ||)

10、随机链表的复制

终章


9、 环形链表 ||

【图解】

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 typedef struct ListNode ListNode;
struct ListNode *detectCycle(struct ListNode *head) {
    //找相遇节点
    ListNode* slow=head;
    ListNode* fast=head;
    while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;
        if(slow==fast)
        {
            //相遇,开始遍历
            ListNode* pcur=head;
            while(slow!=pcur)
            {
                slow=slow->next;
                pcur=pcur->next;
            }
            return slow;
        }
    }
    return NULL;
    
}

10、随机链表的复制

【图解】

【思路】

1、在原链表的基础上复制新链表

2、置random指针

3、(改变next指针指向)将复制链表和原链表断开

cs 复制代码
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

typedef struct Node Node;
//创建新结点
Node* BuyNode(int x)
{
    Node* newnode=(Node*)malloc(sizeof(Node));
    newnode->val=x;
    newnode->next=newnode->random=NULL;

    return newnode;
}
//复制结点
void AddNode(Node* phead)
{
    Node* pcur=phead;
    while(pcur)
    {
        Node* Next=pcur->next;
        //创建新结点
        Node* newnode=BuyNode(pcur->val);
        newnode->next=Next;
        pcur->next=newnode;

        pcur=Next;
    }
}

struct Node* copyRandomList(struct Node* head) {
    if(head==NULL)
    {
        return NULL;
    }
    //第一步:复制结点
    AddNode(head);

    //第二步:置random
    Node* pcur=head;
    while(pcur)
    {
        Node* copy=pcur->next;
        if(pcur->random!=NULL)
        {
            copy->random=pcur->random->next;
        }
        pcur=copy->next;
    }

    //第三步:断开链表
    pcur=head;
    Node* newTail,*newHead;
    newTail=newHead=pcur->next;
    while(pcur->next->next)
    {
        pcur=pcur->next->next;
        newTail->next=pcur->next;
        newTail=newTail->next;
    }
    return newHead;
}

这十道题做完理解透,想不提升都难


完------

------------------------------------------------ 终章 ------------------------------------------------

Lemon_米津玄師_高音质在线试听_Lemon歌词|歌曲下载_酷狗音乐酷狗音乐为您提供由米津玄師演唱的高清音质无损Lemonmp3在线听,听Lemon,只来酷狗音乐!https://t3.kugou.com/song.html?id=cp8Rz2eCPV2

拜拜------

相关推荐
坚持编程的菜鸟7 小时前
LeetCode每日一题——三角形的最大周长
算法·leetcode·职场和发展
Jose_lz7 小时前
C#开发学习杂笔(更新中)
开发语言·学习·c#
Chloeis Syntax7 小时前
接10月12日---队列笔记
java·数据结构·笔记·队列
QT 小鲜肉7 小时前
【个人成长笔记】Qt 中 SkipEmptyParts 编译错误解决方案及版本兼容性指南
数据库·c++·笔记·qt·学习·学习方法
一位代码8 小时前
python | requests爬虫如何正确获取网页编码?
开发语言·爬虫·python
看到我,请让我去学习8 小时前
Qt 控件 QSS 样式大全(通用属性篇)
开发语言·c++·qt
筱砚.8 小时前
【STL——vector容器】
开发语言·c++
lly2024068 小时前
数据访问对象模式(Data Access Object Pattern)
开发语言
std860218 小时前
Rust 与 Python – 这是未来的语言吗?
开发语言·python·rust
Cathy Bryant8 小时前
矩阵乘以向量?向量乘以向量?
笔记·神经网络·考研·机器学习·数学建模