Saturday, June 29, 2013

Write an algorithm to delete the last node of the singly linked list.



Conditions:
·         ‘SingleNode’ is the node representation of singly linked list, where,
struct my_node{      //structure name ‘my_node’
                   int data;    //data field
                   struct my_node *next;      //pointer to next node
                  };
typedef struct my_node SingleNode;    //defining a node of singly linked list ‘SingleNode’
·         ‘phead’ is a head pointer pointing to the first node
·         ‘last’ is a pointer to SingleNode
·         ‘secondlast’ is a pointer to SingleNode
ALGORITHM:
1.       Start
2.       check if the list is empty or not
if phead==NULL
OUTPUT ‘No any node to delete’ and exit
else goto step 3
3.       Set the head pointer to temporary pointer
SET last=phead->next
SET secondlast=phead
4.       Find the last node
SET while(last->next!=NULL)
      { SET last=last->next
        SET secondlast= secondlast->next  }
5.       set the newly last node to NULL
SET secondlast->next= NULL
6.       Display the element of deleted node
OUTPUT last->data
7.       Free the deleted node from the system
SET free(last)
8.       Stop

2 comments: