how to delete node from end of linked list

Given a linked list, delete a node from end of linked list. Here is simple C Program to delete node from end of linked list.

C Program:

#include<stdio.h>
#include<stdlib.h>
 
struct Node
{
 int data;
 struct Node *next;
};
 
/* Function to create new node that take one integer and 
return the address of node */
struct Node *CreateNode(int n)
{
 /* Create a new node in which data is n and pointer next
 is pointing to NULL */
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
 newNode->data = n;
 newNode->next = NULL;
 return newNode;
}
 
struct Node *InsertAtBeginning(struct Node *head, int n)
{
 /* Get new node by calling function CreateNode() */
 /* We can create new node in this function also as
 
struct Node *newNode=(struct Node*)malloc(sizeof(struct Node);
 newNode->data = n;
 newNode->next = NULL;
 */
 struct Node *newNode = CreateNode(n);
 
 /* If head is pointing to NULL then add newNode at the first
 position by pointing head to newNode */
 if(head==NULL)
 {
  head = newNode;
 }
 else
 {
  newNode->next = head;
  head = newNode;
 }
 
 return head;
}
 
struct Node *Delete(struct Node *head)
{
 struct Node *temp=head;
 struct Node *curr = head;
 /* If there is no node in linked lisr */
 if(curr==NULL)
 {
  return head;
 }
 else
 /* If there is only one node in linked list 
 then point head node to head->next */
 if(head->next==NULL)
 { 
  head = temp->next;
  free(temp);
  return head;
 }
 else
 {
 /* If there is more then one node in linked list 
 then reach second last node in linked list and delete
 last node */
  while(curr->next->next!=NULL)
 {
  curr = curr->next;
 }
    temp = curr->next;
    curr->next=NULL;
    free(temp);
    return head;
 }
}
 
void PrintList(struct Node *head)
{
 struct Node *curr = head;
 
 if(curr==NULL)
 {
  printf("List is empty\n");
 }
 else
 {
 while(curr!=NULL)
 {
  printf("%d ",curr->data);
  curr = curr->next; 
 }
 }
     printf("\n");
}
 
int main()
{
 struct Node *head = NULL;
 
 /* Print list when head is pointing to NULL
 or there is no node in list */
 
 PrintList(head);
 
 head = InsertAtBeginning(head,12);
 head = InsertAtBeginning(head,78);
 head = InsertAtBeginning(head,65);
 head = InsertAtBeginning(head,28);
 
 PrintList(head);
 
 head = Delete(head);
 head = Delete(head);
 PrintList(head);
 
 return 0;
}



Popular posts from this blog