Delete Node from beginning of linked list
C Program to delete node from beginning position of linked list. Simple C program to delete nodes.
C Program:
C Program:
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; /* Function to create new node to insert in linked list that take an interger as arguement and return the address of node */ struct Node *CreateNode(int n) { /* Function to create new Node to insert node in linked list */ struct Node *newNode=(struct Node*)malloc(sizeof(struct Node)); newNode->data = n; newNode->next = NULL; return newNode; } struct Node *InsertAtEnd(struct Node *head,int n) { struct Node *newNode = CreateNode(n); struct Node *temp = head; /* If head is pointing to NULL then at node at first position */ if(head==NULL) { head = newNode; } else { /* If there is node/nodes in linked list then reach at the end node of linked list and then point end node to new node */ while(temp->next!=NULL) { temp = temp->next; } /* Connect new node to linked list */ temp->next = newNode; } return head; } void PrintList(struct Node *head) { struct Node *curr = head; /* If head is pointing to NULl it means list is empty */ if(curr==NULL) { printf("List is empty\n"); } else { while(curr!=NULL) { printf("%d ",curr->data); curr = curr->next; } } printf("\n"); } struct Node *Delete(struct Node *head) { struct Node *temp = head; /* If there is not any node in linked then simply return head node */ if(head==NULL) { return head; } else { /* To delete node from beginning of linked list then point head to the next node of head */ head = temp->next; free(temp); } return head; } int main() { struct Node *head=NULL; /*Print list when there is not any node in list or list is empty */ PrintList(head); head = InsertAtEnd(head,54); head = InsertAtEnd(head,65); head = InsertAtEnd(head,49); head = InsertAtEnd(head,98); PrintList(head); head = Delete(head); head = Delete(head); PrintList(head); return 0; }