Monday, March 14, 2011

WAP to Insert Node in Circuler Linked List In Sorted Order

#include
#include

/* structure for a node */
struct node
{
int data;
struct node *next;
};

/* function to insert a new_node in a list in sorted way.
Note that this function expects a pointer to head_ref
as this can modify the head of the input linked list */
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current = *head_ref;

if (current == NULL)
{
new_node->next = new_node;
*head_ref = new_node;
}

/* Special case for the head end */
else if (current->data >= new_node->data)
{
/* If value is smaller than head's value then
we need to change next of last node */
while(current->next != *head_ref)
current = current->next;
current->next = new_node;
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
while (current->next!= *head_ref && current->next->data < new_node->data)
current = current->next;

new_node->next = current->next;
current->next = new_node;
}
}

/* Function to print nodes in a given linked list */
void printList(struct node *start);

int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;

/* start with empty linked list */
struct node *start = NULL;
struct node *temp;

/* Create linked list from the array arr[].
Created linked list will be 1->11->2->56->12 */
for(i = 0; i< 6; i++)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->data = arr[i];
sortedInsert(&start, temp);
}

printList(start);
getchar();
return 0;
}

/* Function to print nodes in a given linked list */
void printList(struct node *start)
{
struct node *temp;

if(start != NULL)
{
temp = start;
printf("\n");
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != start);
}
}



https://ideone.com/NdBum

No comments :