Hi I'm trying to write code for a doubly linked list. I have some trouble understanding linked list arrays and structures. This is what I have, would anyone please be able to help me figure out what I'm doing wrong? Thank you.
/*
* linkstack.c
*
* A stack implemented as a linked list
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int element;
struct Node *next;
struct Node *prev;
} Node;
Node *head = 0;
void print_stack ( )
{
Node *p = head;
printf ("Top:");
while ( p )
{
printf ("[%d]", p->element );
p = p->next;
}
printf (":Bottom\n");
}
void addsorted (int value)
{
Node *n = (Node *)malloc(sizeof(Node));
n->next=NULL;
n->element = value;
if(!head)
{
head = n;
}
else
{
Node *p = head;
if (n->element > head)
{
while(p->next != NULL)
{
if (n->element > p->next)
{
p = p->next;
}
else
{
p->next->prev = n;
n->prev = p->prev;
p->prev = n;
n->next = p;
}
}
p->next = n;
}
}
int main ()
{
addsorted(9);
addsorted(15);
addsorted(4);
print_stack();
return 0;
}
/*
* linkstack.c
*
* A stack implemented as a linked list
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int element;
struct Node *next;
struct Node *prev;
} Node;
Node *head = 0;
void print_stack ( )
{
Node *p = head;
printf ("Top:");
while ( p )
{
printf ("[%d]", p->element );
p = p->next;
}
printf (":Bottom\n");
}
void addsorted (int value)
{
Node *n = (Node *)malloc(sizeof(Node));
n->next=NULL;
n->element = value;
if(!head)
{
head = n;
}
else
{
Node *p = head;
if (n->element > head)
{
while(p->next != NULL)
{
if (n->element > p->next)
{
p = p->next;
}
else
{
p->next->prev = n;
n->prev = p->prev;
p->prev = n;
n->next = p;
}
}
p->next = n;
}
}
int main ()
{
addsorted(9);
addsorted(15);
addsorted(4);
print_stack();
return 0;
}