首页 文章

我不明白在链表中插入新节点的实现

提问于
浏览
-2

在链表实现中,将新节点插入链表通常如下所示:

void push(struct node ** head_ref,int new_data)

/* 1. allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));

/* 2. put in the data  */
new_node->data  = new_data;

/* 3. Make next of new node as head */
new_node->next = (*head_ref);

/* 4. move the head to point to the new node */
(*head_ref)    = new_node;

(我从http://quiz.geeksforgeeks.org/linked-list-set-2-inserting-a-node/获取此代码)

并且节点结构是:

struct node {

int数据;

struct node * next;

};

我不明白的是插入部分的3.和4.所以你让new_node的下一个指针指向头部,然后头部指向new_node?这意味着下一个指针指向new_node?

这似乎是一个愚蠢的问题,但我无法理解它,所以我希望有人可以向我解释 . 谢谢 .

3 回答

  • 0

    如果我理解正确,这是你的情景?

    http://www.kkhsou.in/main/EVidya2/computer_science/comscience/313.gif

    您的列表只是一个带有下一个指针的链表,直到列表的最后一个项为null作为指针

    步骤3使您的新节点指向此操作之前列表开头的第二个项目

    步骤4使列表头指向新节点

    希望这可以帮助

  • 0

    / * 1.分配节点/结构节点new_node =(struct node *)malloc(sizeof(struct node));

    / * 2.输入数据* / new_node-> data = new_data;

    / * 3.将新节点的下一个设为head * / new_node-> next =(* head_ref);

    / * 4.将头部移动到指向新节点* /(* head_ref)= new_node;

    在步骤1和2中,创建一个新节点并为其分配数据 .

    如果列表为空,则* head_ref将为null . 或者如果它有任何元素,它将指向Lets举个例子

    Now 
    *head_ref is null
    when input is 1
    newnode.data=1
    newnode.next=null
    *headref=newnode 
    now your *headref points to the latest node that is added ,this happens with step4
    
    When you insert 2
    newnode.data=2
    newnode.next=*headref(to the node which is 1)
    newnode=*headref
    now your list is
    1->2(*headref)
    now if you add 3 here
    it becomes
    1->2->3(*headref)
    

    希望你能理解

  • 0

    而不是向你解释,我将建议一种技巧,帮助你自己解决问题 .

    • 拿一张纸,一支铅笔和一块橡皮擦 .

    • 在纸上画一个框来表示算法中的每个变量

    • 绘制初始链表:

    • 绘制一个框以表示初始链接列表中的每个现有 node .

    • 将每个框分成表示字段的子框 .

    • 在每个字段中写入一个值或一个代表指针"from"结尾的点 .

    • 对于每个指针,在指向的东西(例如 node )上绘制一条线,并在"to"末端放置一个箭头 . NULL指针只是一个点 .

    • 现在执行算法 .

    • 每次分配新的 node 时,绘制一个新框 .

    • 每次为变量或字段分配内容时,请擦除当前值并在新值或新点/箭头中写入/绘制 .

    如果您仔细而系统地执行此操作,您将能够准确地可视化列表插入算法正在执行的操作 .

    同样的技术可用于可视化任何列表/树/图算法...模块化你将它全部放到一张纸上的能力,以及纸张能够经受住反复擦除的能力 .


    (这种铅笔和纸的方法非常“老派” . 就像在我学习20世纪70年代的程序时,这是我们被教导要做的 . 稍微更现代的方法是使用白板...)

相关问题