繁体   English   中英

将节点插入链表

[英]inserting a node into a linked list

假设结构列表和节点定义为

struct list {struct node *a;};


struct node { int value;     
              struct node *next;};

以下函数将整数 e 作为第一个元素插入 l

void insert_first(int e, struct list *l){
   struct node * r = malloc(sizeof(struct node));
   r->value = e;
   r->next = l->a;
   l->a = r;}

示例:原始列表“b”:1 2 3 4

调用 insert_first(3,*b) 后

列表“b”:3 1 2 3 4

insert_first 非常简单; 但是,我很难弄清楚如何编写一个函数 insert_last 来插入一个数字作为列表的最后一个元素。

示例:原始列表“b”:1 2 3 4

调用 insert_last(3,*b) 后

列表“b”:1 2 3 4 3

提前感谢您的任何帮助。

您需要保存原始 HEAD 节点并遍历 list 。 希望这段代码能帮到你。

struct node {
           int value;
           struct node *next;
    };

    struct list {struct node *a;};

    struct node *insert_last(int e, struct list *l) {
    /* Store the initial head of the list */
    struct list *org_head = head;
    struct node *r = malloc(sizeof(struct node));
    r->value = e;
    r->next = NULL /* Assign next pointer of current node to NULL */

    /* If the head is initially NULL, then directly return the new created node (r) as the  head of a linked list with only one node */

    if(head == NULL)
        {
            return r;
        }

    /* While we do not reach the last node, move to the next node */

      while(head -> next != NULL)
            head = head -> next;
        /* Assign the 'next' pointer of the current node to the "r" */
        head->next = r;
        /* return the original head that we have stored separately before */
        return org_head;
    }

一种方法是遍历列表直到找到尾部。 像这样的东西:

void insert_last(int e, struct list *l)
{
    // "iter" Will iterate over the list.
    struct node *iter = l->a;
    struct node *new_node = malloc(sizeof(struct node));
    // Advice: ALWAYS check, if malloc returned a pointer!
    if(!new_node) exit(1); // Memory allocation failure.
    new_node->value = e;
    new_node->next = NULL;
    if(iter){
        // Loop until we found the tail.
        // (The node with no next node)
        while(iter->next) iter = iter->next;
        // Assign the new tail.
        iter->next = new_node;
    }else{
        // The list was empty, assign the new node to be the head of the list.
        l->a = new_node;
    }
}

编辑:我在你的代码中看到的东西,真的让我很痒:在使用 malloc 时,总是检查你是否真的得到了一个指针(检查指针是否为 NULL)。 如果 malloc 无法分配内存,无论是由于缺少内存还是其他一些严重错误,它都会向您抛出一个 NULL 指针。 如果您不检查这一点,您最终可能会遇到一些非常讨厌、难以检测的错误。 只是一点提醒!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM