Linked list implementation in c without using double-pointer

怎甘沉沦 提交于 2019-12-06 13:17:14

Yes, you can rewrite this code using only single pointers, but you would have to change the semantic of your API and the pattern in which it is used.

Essentially, you replace the second level of indirection in

void push(struct node** head_ref, int new_data)

with a client-side assignment, i.e.

struct node* push(struct node* head, int new_data)

This means that instead of

push(&head, num);

the caller will have to write

head = push(head, num);

Same goes for the implementation of append.

Replace (&head,6) with (head,6).As you are not passing the address of the head, on receiving end you have push(struct node* head, int new_data).Rest all have been clarified by above given answer

Another solution is to create an empty node called head, and then create a pointer to that node called list. You can then pass list to all of the functions, like this

#include <stdio.h>
#include <stdlib.h>

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

void push(struct node *list, int new_data)
{
    struct node* new_node = malloc(sizeof(struct node));
    new_node->data = new_data;
    new_node->next = list->next;
    list->next = new_node;
}

void append(struct node *list, int new_data)
{
    while ( list->next != NULL ) 
        list = list->next;
    push( list, new_data );
}

void printList(struct node *node)
{
    for ( node=node->next; node != NULL; node=node->next )
        printf(" %d ", node->data);
    printf( "\n" );
}

int main( void )
{
    struct node head = { 0, NULL };
    struct node *list = &head;

    append(list, 6);
    push(list, 7);
    push(list, 1);
    append(list, 4);
    printf("\n Created Linked list is: ");
    printList(list);
    getchar();
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!