#include <stdio.h>
#include <stdlib.h>
/*
#include <conio.h>
*/
struct dnode
{
struct dnode *prev;
struct dnode *next;
int data;
};
void display(struct dnode *p);
void append (struct dnode **s, int num);
void free_all (struct dnode *p);
int main (void)
{
struct dnode *p=NULL;
append(&p, 2);
append(&p, 5);
append(&p, 7);
append(&p, 6);
append(&p, 8);
append(&p, 9);
append(&p, 3);
append(&p, 1);
append(&p, 4);
append(&p, 0);
display(p);
free_all(p);
/*
getch();
*/
return 0;
}
void display(struct dnode *p)
{
while(p)
{
printf("%d\n", p->data);
p=p->next;
}
printf("\n");
}
void append(struct dnode **s, int num)
{
struct dnode *r;
if (!s)
return;
r = (struct dnode*)malloc(sizeof *r);
if (!r)
{
fprintf(stderr, "Cannot allocate storage for dnode **s\n");
display(*s);
free_all(*s);
exit(EXIT_FAILURE);
}
r->next=NULL;
r->prev=NULL;
r->data=num;
if (*s == NULL)
{
/* first and only node: initialise list head */
*s = r;
}
else if ((*s)->data > num)
{
/* r already is in the right place, so add links
** and set r to be the new list head. */
r->next = *s;
(*s)->prev = r;
*s = r;
}
else
{
/* iterate until the right position for r is
** found, then link it in. */
struct dnode *p;
for (p=*s; p->next; p=p->next)
{
if (p->next->data > num)
{
p->next->prev = r;
break;
}
}
r->prev = p;
r->next = p->next;
p->next = r;
}
}
void free_all (struct dnode *p)
{
struct dnode *tmp;
if (p && p->next)
for (tmp = p->next; tmp; )
{
if (tmp->next)
{
tmp = tmp->next;
free(tmp->prev);
}
else
{
free(tmp);
tmp = NULL;
}
}
if (p && p->prev)
for (tmp = p->prev; tmp; )
{
if (tmp->prev)
{
tmp = tmp->prev;
free(tmp->next);
}
else
{
free(tmp);
tmp = NULL;
}
}
free(p);
}
Pradyut
http://pradyut.tk
http://groups.yahoo.com/group/d_dom/
http://groups-beta.google.com/group/oop_programming
No comments:
Post a Comment