0

I have a function below that adds a node to the end of a linked list.

struct node {
char customer[100];
struct node *next;
}node;

struct node *add_name(struct node *tail, struct node *new_node) 
{
    struct node *temp;
    if(tail==NULL) {
        tail=new_node;
    }
    else {
        temp=tail;
        while (temp->next!=NULL) {
            temp=temp->next;
        }
        temp->next=new_node; //tail points to new node
    }
return tail;
}

I'm now trying to write a function that will print and then delete the first node of the linked list. However, my problem is I don't know how to do that considering I'm only looking at the end so far, not the beginning. I know I need to declare a pointer *head to point to the first node, but how would I do that and how do I know that it's going to point to the first node? This is my first time working with linked lists, so I'm still a bit confused by them.

tmp657
  • 25
  • 2
  • 8
  • 1
    Go through this, [here](http://www.learn-c.org/en/Linked_lists) – Akash K. Apr 19 '17 at 03:44
  • You should have a pointer to head node. If not the linkedlist will be useless. Use that head node to get first element. From the first node, store customer value and next value in variables and set that next value pointed by the header as first value. Then print customer value and you are good to go. – Dimuth Tharaka Menikgama Apr 19 '17 at 03:48
  • Possible duplicate of [Deleting first node in linked list has problems](http://stackoverflow.com/questions/19077036/deleting-first-node-in-linked-list-has-problems) – David C. Rankin Apr 19 '17 at 04:54

1 Answers1

4

You should not pass the tail of the list when adding new element. The only thing you need to know about the list is its head. Inserting should look like this:

void insert(node **head, char *customer)
{
    node *new_node = malloc(sizeof(node));

    if(!new_node)
    {
        printf("Memory allocation failed!\n");
        exit(1);
    }
    new_node->data = customer;
    new_node->next = NULL;

    node *temp = *head;

    if(!temp)
        *head = new_node;
    else
    {
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = new_node;
    }
    return ;
}

When you insert it this way, delete could look something like this:

void deleteHead(node **head)
{
    node *temp = *head;
    temp = temp->next;
    free(head);
    *head = temp;
}

You create temp so you can store the address of element next to head, which is about to become head. Then you delete whats in head, and declare head to be temp->next. Now head points to what used to be second element in the list.

sstefan
  • 385
  • 4
  • 15