开发者

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

开发者 https://www.devze.com 2022-12-15 01:37 出处:网络
What is wrong with addAtBegin? The list seems to be correct after assigning the newly created node to start, but when control returns t开发者_JAVA百科o main, the new value is not saved.

What is wrong with addAtBegin? The list seems to be correct after assigning the newly created node to start, but when control returns t开发者_JAVA百科o 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;
}


Looks like another list question to me, with the same answer as most of them - start should be a pointer to a pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消