Lexicographical order using Linked list

Lexicographical order using Linked list


Write a program to sort the string in lexicographical order
Sample Input    : bala
Sample Output : aabl

Sample Input    : jobatupdate
Sample Output : aabdejopttu

Constraint : O(n)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
struct node //node structure
{
    char data;
    struct node *next;
};
struct node *newnode,*start,*tptr,*prev;
void addNode(char character) 
{
    newnode=(struct node*)malloc(sizeof(struct node)); //node creation
    newnode->data=character;
    newnode->next=NULL;
    if(start==NULL) //first node
        start=newnode;
    else
    {   //ordering node in lexicographical order
        for(prev=NULL,tptr=start;tptr && tptr->data < newnode->data;prev=tptr,tptr=tptr->next);
        if(tptr==start) //insert at beginning
        {
            newnode->next=start;
            start=newnode;
        }
        else //insert at middle or end
        {
            prev->next=newnode;
            newnode->next=tptr;
        }
    }
}
int main()
{
    char str[20];int size;
    gets(str);
    size=strlen(str);
    for(int i=0;i<size;addNode(str[i]),i++);
    for(tptr=start;tptr;printf("%c",tptr->data),tptr=tptr->next);
    return 0;
}

OUTPUT :




0 comments