I have the following question. My code is given below. Two problems I'm having with is:
1.How can I link the alphabets without using the arrays? Maybe use a for loop?
2.How to reverse the order of the linked list
Using the following struct:
typedef char DATA;
struct node
{
DATA d;
struct node * next;
};
Write a program to build a single linked list using a loop. Your list should be ordered so
that the last item added is at the beginning of the list
note: I did not use typedef in my code as I'm new to structures and it just confuses me at the moment
Code:
#include <stdio.h>
#include <stdlib.h> /*for malloc()*/
#include <string.h>
int main()
{
struct node{
char d[2];
struct node *next; /*pointer to next structure*/
};
char *node[26]={"A","B","C","D","E","F",
"G","H","I","J","K","L",
"M","N","O","P","Q","R",
"S","T","U","V","W","X",
"Y","Z"};
struct node *first_item; /*pointer first_item to first structure*/
struct node *current_item;
struct node *new_item;
int index=0;
/*allocating memory for first structure*/
first_item=(struct node*)malloc(sizeof(struct node));
/*creating first structure*/
current_item=first_item;
/*fill the structures*/
while(index<26)
{
strcpy(current_item->d,node[index]);
index++;
if (index<26)
{
new_item=(struct node*)malloc(sizeof(struct node));
current_item->next=new_item; /*set the address of new_item to pointer next*/
current_item=new_item;
}
else
{
current_item->next=NULL;
break;
}
}
/*display the results*/
current_item=first_item;
index=1;
while(current_item)
{
printf("Structure %d: ",index++);
printf("%s\n",current_item->d);
current_item=current_item->next;
}
getchar();
return(0);
}