【问题标题】:trying to understand this linkedlist insertion code试图理解这个链表插入代码
【发布时间】:2015-05-04 20:53:47
【问题描述】:

我有这个代码

struct Node {
   int data;
   struct *Node next;
};

struct Node *head;

void insert(int x) {
    node* temp = (node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = head;
    head = temp;
}

int main()
{
     head = NULL;
}

我正在关注这个video,看起来代码有效。不过我很难把它放在一起。

我们有一个节点头,它在 main 方法中最初设置为 NULL。

linkedlist 包含一个 int 和 next。此插入代码将数据设置为 int 并位于 head 旁边。然后它设置头部温度。

由于我们将 temp.next 设置为 head 然后 head = temp ,这难道不会让 head 得到 int ,然后让它一遍又一遍地指向自己吗?

到目前为止,我只对 linkedlist 进行了迭代,其中最后一个 next 为 NULL。

【问题讨论】:

    标签: c


    【解决方案1】:

    此代码在链表的开头插入一个项目 - 它创建一个新节点,设置其数据,并使其next 指向当前head

    【讨论】:

      【解决方案2】:

      没有。

      node* temp = malloc(sizeof(struct node));
      temp->data = x;
      

      我们有一个新节点,并且已经设置了它的值。

      temp->next = head;
      

      head(如果有)将出现在列表中的此元素之后。这意味着这应该是我们的新head

      head = temp;
      

      现在就是这样。

      如果 headNULL,则此列表没有 next 条目,正如预期的那样。

      如果head 不是NULL,则此节点是新的头,它的next 指向列表中的第二个 元素(旧的head)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-30
        • 1970-01-01
        • 2017-08-10
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        相关资源
        最近更新 更多