Saturday, June 29, 2013

Write an algorithm to insert a new node at the end of a 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
ALGORITHM:
1.       Start
2.       create a new node
SET ptr= (SingleNode*) malloc (sizeof(SingleNode))
3.       Add the element ‘item’ in the data field of the node
SET ptr->data= item
4.       Set the pointer field of the new node to NULL
SET ptr->next=NULL
5.        If phead==NULL
SET phead=ptr
else
SET last=phead
find the last node
SET while(last->next!=NULL)
                last=last->next
6.       Add the new node at the end of list
SET last->next=ptr
7.       Stop

4 comments: