C beginner here, trying to learn more about Linked Lists.
The following code is supposed to create a circular doubly linked list from a structure called "soldier". The int n
is important since it determines the number of nodes created, each node contains an int data
with the value of n
, as long as n=>1
.
So when the user enters n=6
, the linked list will look like:
6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1
^ ^
|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
I have been stuck here for a while now. I am trying to see what I am missing but can't see it. Everything compiles files, except that I get only the following error: [Error] expected '=', ',', ';', 'asm' or '__attribute__' before '*' token
#include<stdio.h>
#include<stdlib.h>
typedef struct nod{
int data;
struct nod *prev, *next;
}soldier;
soldier *head;
void soldier* create_soldier (int sequence){
if(head->data==NULL) //when the linked list starts
head->data = sequence;
else{
soldier *temp;
soldier *t;
temp= (soldier *) malloc(sizeof(soldier));
temp->data = sequence;
temp->next = NULL;
t= head; //Traversing
while (t->next != NULL)
t= t->next;
if(temp->data==1){ //for the rear end of the array to link back to the head
t->next = temp;
temp->prev = t;
temp->next = head;
head->prev = temp;
}
else{
t->next = temp;
temp->prev = t;
}
}
}
void display(soldier* head){
soldier *t;
t=head;
while (t->next != head){
printf("%d", t->data);
t= t->next;
}
}
void display(soldier* head){
soldier *t;
t=head;
while (t->next != head){
printf("%d", t->data);
t= t->next;
}
}
int main()
{
int n, k;
printf("Enter the number of soldiers to be executed");
scanf("%d", &n);
printf("Enter the number of soldiers to be skipped");
scanf("%d", &k);
for ( ; n>= 1; n--)
create_soldier(n);
display(head);
return 0;
}