简体   繁体   中英

How do I insert a node at the beginning of a linked list?

What is wrong with addAtBegin ? The list seems to be correct after assigning the newly created node to start , but when control returns to main , the new value is not saved.

typedef struct node
{
    int data;
    struct node *link;
}node;

node* createList(int data)
{
    node *tempNode=(node*)malloc(sizeof(node));
    tempNode->data=data;
    tempNode->link=NULL;
    return tempNode;
}

void addAtBegin(node *start,int data)
{
    node *addedNode=(node *)malloc(sizeof(node));
    addedNode->data=data;
    addedNode->link=(start==NULL)?NULL:start;
    start=addedNode;
}

void displayNodes(node *start)
{
    node *startCopy=start;
    while(startCopy!=NULL)
    {
        printf("%d\t",startCopy->data);
        startCopy=startCopy->link;
    }
    printf("\n");
}

int main( )
{   
    node *start=createList(2);
    addAtBegin(start,1);
    displayNodes(start);
    return 0;
}

对我来说,这似乎是另一个列表问题,与大多数问题的答案相同-start应该是一个指向指针的指针。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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