Singly Linked List deletion

Last Updated on

delete first node from single linked list

Singly Linked List deletion

import code from the create and display nodes and getnode function to assign data click here

  1. create a function deletebeg( )
  2. create a *temp pointer from structure NODE,initialize temp with head
initialize temp with head

3.move head to the next node using the address of next node (head=head->next)

move head to the next node

4.delete the temp node using the free keyword

Singly Linked List deletion 1

5.first node will be deleted

Singly Linked List deletion 2
temp = head;
head = temp -> next;
free(temp);
printf("\n Node deleted ");

code to delete first node from single linked list

void deletebeg()
{
	node *temp;
	if(head == NULL)
	{
		printf("\n No nodes are exist..");
		return ;
	}
	else
	{
		temp = head;
		head = temp -> next;
		free(temp);
		printf("\n Node deleted ");
	}
}

delete last node from single linked list

import code from the create and display nodes and getnode function to assign data click here

Singly Linked List deletion 3
  1. create a function deleteend( )
  2. create a *temp ,*prev pointer from structure NODE
  3. initialize temp and prev with head pointer
initialize temp and prev with head pointer

4.create a while loop with condition (temp->next!=NULL),

5.intitalize prev with temp and move temp pointer to next node using the next address field

6.we are using while loop to move prev pointer to the second element from the ending and temp pointer to the last node

Singly Linked List deletion 4

7.make the prev node’s next address field as NULL

8.delete last node(temp pointed node) using free keyword in c

delete last node

9.last node will be deleted

Singly Linked List deletion 5
temp = head;
prev = head;
while(temp -> next != NULL)
{
	prev = temp;
	temp = temp -> next;
}
prev -> next = NULL;
free(temp);

code to delete last node from single linked list

void deleteend()
{
	node *temp, *prev;
	if(head == NULL)
	{
		printf("\n Empty List..");
		return ;
	}
	else
	{
		temp = head;
		prev = head;
		while(temp -> next != NULL)
		{
			prev = temp;
			temp = temp -> next;
		}
		prev -> next = NULL;
		free(temp);
		printf("\n Node deleted ");
	 }
}