Saturday, June 29, 2013

Write an algorithm to count total number of nodes in 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
·         ‘count’ is a integer variable initially set to zero
ALGORITHM:
1.       Start
2.       check if the list is empty or not
if phead ==NULL
OUTPUT ‘Zero nodes’ and exit
else goto step 3
3.       Set the head pointer to a temporary variable
last=phead
4.       Traverse till the last node
SET while(last->next!= NULL)
{ increase the node count by 1
SET count++
point to the next node in the list
SET last=last->next
}
5.       Increase the value of count by 1 for last node if the list has more than one node otherwise this condition is applicable if the list has exactly one node.
6.       Display the total count of nodes
OUTPUT count
7.       Stop

No comments:

Post a Comment