Saturday, June 29, 2013

Write an algorithm to insert a new node at the beginning 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
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.        If phead==NULL
SET ptr->next=NULL
else
SET ptr->next=phead
5.       Set the head pointer to the first node
SET phead=ptr
6.       Stop

2 comments: