GreedyAi
GreedyAi

Reputation: 2839

Want to make linked list function that deletes first Node

This is my code. I made three functions for adding a new node, inserting a new node between two others, and one deleting, but I dont know how to delete the first node. I dont even have any idea.

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

struct Node
{
    int data;   
    struct Node *next;  
};
void insert(Node* insertafter, Node* newNode);
void add(Node* llist,Node* newNode);
void deleteafter(Node *llist);
void deletefirts();
int main()
{ 
    struct Node *llist;
    struct Node *newNode;
    newNode = (Node*)malloc(sizeof(struct Node));
    newNode->data = 13;
    struct Node *newNode2;
    newNode2 = (Node*)malloc(sizeof(struct Node));
    newNode2->data = 14;
    llist = (Node*)malloc(sizeof(struct Node));
    llist->data = 10;
    llist->next = (Node*)malloc(sizeof(struct Node));
    llist->next->data = 15;
    llist->next->next = NULL;
    insert(llist,newNode);
    add(llist,newNode2);
    if(llist->next == NULL)
    printf("shecdoma");
    struct Node *cursor = llist;
    while (cursor != NULL) 
    {
        printf("%d\n", cursor->data);          
        cursor = cursor->next;
    } 
    system("pause");
    return 0;   
}            
void insert(Node* insertafter, Node *newNode)
{
     newNode->next = insertafter->next;
     insertafter->next = newNode;
}
void add(Node* llist,Node *newNode)
{
     if(llist->next == NULL)
     {
     llist->next = newNode;
     newNode->next = NULL;
     }
     else
     {
       while(llist->next != NULL)                   
       {  
          llist = llist->next; 
       }
       add(llist,newNode);
     }

void deleteafter(Node *llist)
{
 if(llist->next != NUll)   
 llist->next = llist->next->next;   
}
void deletefirst(); 
{
}

Upvotes: 1

Views: 8468

Answers (2)

paxdiablo
paxdiablo

Reputation: 881543

You can use something like:

void deletefirst (struct Node **head) {
    struct Node *tmp = *head;            // save old head for freeing.
    if (tmp == NULL) return;             // list empty? then do nothing.
    *head = tmp->next;                   // advance head to second node.
    free (tmp);                          // free old head.
}

You pass in the pointer to the head so that you can change it. Deleting nodes other than the first does not require this but deleting the first node does.

You set up a temporary pointer to the head so you free it, then you change the head to point to its next element. Then you free the old head and return.

Upvotes: 7

George Kastrinis
George Kastrinis

Reputation: 5182

void deleteFirst(Node** list)
{
  Node* temp = *list;
  if (*list != NULL)
  {
    *list = (*list)->next;
    free(temp);
  }
}

Upvotes: 2

Related Questions