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
Example 3: Travelling Salesman problem Given: n associated cities and distances among them Find: tour of minimum length that visits all of city. Solutions: How several

State  in brief about assertion Assertion: A statement which should be true at a designated point in a program.

In this example, suppose the statements are simple unless illustrious otherwise. if-then-else statements if (cond) { sequence of statements 1 } else { sequence of st

Need help with Data Structures assignment requiring C++ program

A linked list can be of the following types:-  Linear linked list or one way list Doubly linked list or two way list. Circular linked list Header linked list

Phong Shading Phong shading too is based on interpolation, but instead of interpolating the colour value, it is the normal vector, which is interpolated for each point and a co

The simplest implementation of the Dijkstra's algorithm stores vertices of set Q into an ordinary linked list or array, and operation Extract-Min(Q) is just a linear search through


Arrays are simple, however reliable to employ in more condition than you can count. Arrays are utilized in those problems while the number of items to be solved out is fixed. They

Write a program that uses the radix sort to sort 1000 random digits. Print the data before and after the sort. Each sort bucket should be a linked list. At the end of the sort, the