This is a cursor-based implementation of list inserting at the end. In the program below, the output the program will show me is the last element of my input. It is suppose to show all elements from the first input to the last. Also, after two inputs, when inserting, it will skip everything and print "no available heap". It should not do that because the heapspace is 50.
I didnt post the view function to make the post here shorter. The problem is not in there anyway. I have tested it many times.
#include<stdio.h>
#include<conio.h>
#define max 50
typedef struct
{
int elem;
int next;
}heapspace[max];
typedef struct
{
heapspace h;
int avail;
}virtualheap;
typedef int list;
void initialize(virtualheap *vh);
void insert_end(virtualheap *vh, list *l, int x);
void initialize(virtualheap *vh)
{
int n = 0;
vh->avail = n;
for(; n < max - 1; vh->h[n].next = n++);
vh->h[n].next = -1;
}
void insert_end(virtualheap *vh, list *l, int x)
{
int p, temp;
if(vh->avail != -1)
{
vh->h[vh->avail].elem = x;
temp = vh->avail;
vh->avail = vh->h[vh->avail].next;
for(p = *l; p != -1; p = vh->h[p].next);
vh->h[temp].next = -1;
if(*l == -1)
*l = temp;
else
vh->h[p].next = temp;
}
else
printf("No available heap\n");
}
void main(void)
{
virtualheap vh;
list l = -1;
int x;
char ans;
initialize(&vh);
do
{
printf("What do you want to put? \n");
scanf("%d", &x);
insert_end(&vh, &l, x);
printf("Do you want to continue? \n");
ans = getch();
}while(ans == 'Y' || ans == 'y');
view(vh, l);
}
Please help me. Thank you!