Write an algorithm insert, Data Structure & Algorithms

Q. Write an algorithm INSERT which takes a pointer to a sorted list and a pointer to a node and inserts the node into its correct position or place in the list. 

Ans:

/* structure containing  the data part and link part */

struct node

{

int data ;

struct node *link ;

} ;

/* Following the inserts node to an ascending order linked list

*/

void INSERT ( struct node **q, int num )

{

struct node *r, *temp = *q ;

r = malloc ( sizeof ( struct node ) ) ;

r -> data = num ;

/* if list is empty or if new node is to be inserted before the first node */

if ( *q == NULL || ( *q ) -> data > num )

{

*q = r ;

( *q ) -> link = temp ;

}

else

{

/* traverse the entire linked list to search or found the position to insert the

new node */

while ( temp != NULL )

{

if ( temp -> data <= num && ( temp -> link -> data > num ||

temp -> link == NULL ))

{

r -> link = temp -> link ;

temp -> link = r ;

return ;

}

temp = temp -> link ; /* go to the next node */ }

}

}

Posted Date: 7/10/2012 5:54:36 AM | Location : United States







Related Discussions:- Write an algorithm insert, Assignment Help, Ask Question on Write an algorithm insert, Get Answer, Expert's Help, Write an algorithm insert Discussions

Write discussion on Write an algorithm insert
Your posts are moderated
Related Questions
how to creat atm project by using linked list?

how to write a pseudo code using Kramer''s rule

implement multiple stack in single dimensionl array.write algorithms for various stack operation for them

Define a B-Tree Justas AVL trees are balanced binary search trees, B-trees are balanced M-way search trees. A B-Tree of order M is either the empty tree or it is an M-way searc

write aprogram for random -search to implement if a[i]=x;then terminate other wise continue the search by picking new randon inex into a

Q1. Define a sparse matrix. Explain different types of sparse matrices? Evaluate the method to calculate address of any element a jk of a matrix stored in memory. Q2. A linear


A company is carrying out a survey by observing traffic at a road junction. Every time a car, bus or lorry passed by road junction it was noted down. 10 000 vehicles were counted d

Simplifying Assumptions of wire frame representation Neglect colour - consider Intensity: For now we shall forget about colour and restrict our discussion just to the intensi

The Linked list is a chain of structures wherein each structure contains data in addition to pointer, which stores the address (link) of the next logical structure in the list.