在链表的尾部插入新节点

时间:2016-11-19 17:35:20

标签: c

所以我在将一个节点插入链表的尾部时遇到了麻烦。我理解这个概念,我相信我的代码是正确的,但我的程序一直在崩溃。我在main中创建了一个列表,其中包含一个将新节点插入列表头部的函数。我对此没有任何问题,只是函数插入尾部。这是下面的代码。

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
    int number;
    struct node * next;
} Node;

typedef Node * Nodeptr;

void insertnode_tail(Nodeptr head);
Nodeptr find_last(Nodeptr head);

void insertnode_tail(Nodeptr head) // function to insert node at the tail.
{
    Nodeptr here = find_last(head);
    Nodeptr newentry = NULL;
    int n = 0;

    printf("Enter the value to be assigned to the new entry? \n");
    scanf("%d", &n);

    if((newentry = malloc(sizeof(Node))) == NULL) {
    printf("No Memory\n");
    exit(0);
    }

    newentry -> number = n;
    newentry -> next = NULL;
    here -> next = newentry;
    traverse1(head);
}


Nodeptr find_last(Nodeptr head) // Function to return the last node of list
{
    Nodeptr aux = head;
    int n = 0;
    while(aux != NULL) {
    aux = aux->next; // moves the aux pointer along the list
    n++;
 }

 return aux;
}

3 个答案:

答案 0 :(得分:1)

find_last()函数中你应该写 -

while(aux->next != NULL)

所以更新的功能是 -

Nodeptr find_last(Nodeptr head) // Function to return the last node of list
{
    Nodeptr aux = head;
    int n = 0;
    while(aux->next != NULL) {
    aux = aux->next; // moves the aux pointer along the list
    n++;
 }

 return aux;
}

您的程序崩溃了,因为您将NULL值作为最后一个节点返回。

答案 1 :(得分:1)

您的find_last函数始终返回NULL。 while循环中的条件应为while (aux->next!= NULL)

答案 2 :(得分:1)

函数find_last总是返回NULL

Nodeptr find_last(Nodeptr head) // Function to return the last node of list
{
    Nodeptr aux = head;
    int n = 0;
    while(aux != NULL) {
    aux = aux->next; // moves the aux pointer along the list
    n++;
 }

 return aux;
}

因为它内部的循环仅在循环条件

时停止迭代
    while(aux != NULL) {
aux等于NULL时,

为false。

因此,在函数insertnode_tail的这个语句中,尝试取消引用NULL指针。

here -> next = newentry;

因此该函数具有未定义的行为。

一般来说,这些功能无效。问题是如果节点被附加到空列表,则必须更新头部。这意味着必须通过引用将头传递给函数。

可以通过以下方式定义函数

Nodeptr * find_last( Nodeptr *head ) // Function to return the last node of list
{
    while( *head ) head = &( *head )->next;

    return head;
}

void insertnode_tail( Nodeptr *head ) // function to insert node at the tail.
{
    Nodeptr *here = find_last( head );

    int n = 0;

    printf("Enter the value to be assigned to the new entry? \n");
    scanf("%d", &n);

    if( ( *here = malloc( sizeof( Node ) ) ) == NULL) 
    {
        printf("No Memory\n");
        exit(0);
    }

    ( *here )->number = n;
    ( *here )-> next = NULL;

    traverse1(*head);
}