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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
int data;
struct Node *prev;
struct Node *next;
};
struct List
{
struct Node *head;
struct Node *tail;
};
void Init(struct List *L)
{
L->head = NULL;
L->tail = NULL;
}
int IsEmpty(struct List L)
{
return L.head == NULL;
}
void InsertLast(struct List *L,int dd)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node ));
newNode->data = dd;
newNode->next = NULL;
if(L->tail == NULL)
L->head = newNode;
else
L->tail->next = newNode;
newNode->prev = L->tail;
L->tail = newNode;
}
void DeleteFirst(struct List *L)
{
struct Node *temp;
if(L->head != NULL)
{
temp = L->head;
if(L->head->next == NULL)
L->tail = NULL;
else
L->head->next->prev = NULL;
L->head = L->head->next;
free(temp);
}
}
void DisplayForward(struct List L)
{
struct Node *current = L.head;
int counter = 0;
printf("List(first-->last): ");
while(current != NULL)
{
printf("%d ",current->data);
counter++;
current = current->next;
}
printf("\n");
printf("Number of nodes on the list : %d\n",counter);
}
void DisplayBackward(struct List L)
{
struct Node *current = L.tail;
int counter = 0;
printf("List(last-->first): ");
while(current != NULL)
{
printf("%d ",current->data);
counter++;
current = current->prev;
}
printf("\n");
printf("Number of nodes on the list : %d\n",counter);
}
void BSTinsert(struct Node *x, struct Node **t)
{
if((*t) == NULL)
(*t) = x;
else if((*t)->data == x->data)
BSTinsert(x,&((*t)->prev));
else if((*t)->data < x->data)
BSTinsert(x,&((*t)->next));
else
BSTinsert(x,&((*t)->prev));
}
void BSTtoDLL(struct Node *t,struct List *L)
{
if(t != NULL)
{
BSTtoDLL(t->prev,L);
if(L->head == NULL)
L->head = t;
else
L->tail->next = t;
t->prev = L->tail;
L->tail = t;
BSTtoDLL(t->next,L);
}
}
void BSTSort(struct List *L)
{
struct Node *temp;
struct Node *T = NULL;
while(L->head != NULL)
{
temp = L->head;
if(L->head->next == NULL)
L->tail = NULL;
else
L->head->next->prev = NULL;
L->head = L->head->next;
temp->prev = NULL;
temp->next = NULL;
BSTinsert(temp,&T);
}
BSTtoDLL(T,L);
}
int main(void) {
// your code goes here
struct List L;
int k,n,m;
Init(&L);
srand(time(NULL));
scanf("%d %d",&n,&m);
for(k=0;k<n;k++)
InsertLast(&L,rand()%m);
DisplayForward(L);
DisplayBackward(L);
BSTSort(&L);
DisplayForward(L);
DisplayBackward(L);
while(!IsEmpty(L))
DeleteFirst(&L);
system("PAUSE");
return 0;
}
|