is there a quicker way to fill the list with A,B,C,...,Y,Z whithout doing all this?
1.
#include <stdio.h>
2.
#include <stdlib.h>
3.
#include <string.h>
4.
#include <malloc.h>
5.

6.
struct node /* Declaration of structure "node" */
7.
{
8.
char letter[1];
9.
struct node *next ;
10.
};
11.

12.
struct node *start = NULL;
13.

14.
main(void)
15.
{
16.
struct node *current = start;
17.
struct node *new_ptr;
18.

19.
new_ptr = (struct node *)malloc(sizeof(struct node));
20.
new_ptr->next = NULL;
21.
strcpy(new_ptr->letter, "A");
22.
start = new_ptr;
23.
current = new_ptr;
24.

25.
new_ptr = (struct node *)malloc(sizeof(struct node));
26.
new_ptr->next = NULL;
27.
strcpy(new_ptr->letter, "B");
28.
current->next = new_ptr;
29.
current = new_ptr;
30.

31.
new_ptr = (struct node *)malloc(sizeof(struct node));
32.
new_ptr->next = NULL;
33.
strcpy(new_ptr->letter, "C");
34.
current->next = new_ptr;
35.
current = new_ptr;
36.

37.
new_ptr = (struct node *)malloc(sizeof(struct node));
38.
new_ptr->next = NULL;
39.
strcpy(new_ptr->letter, "D");
40.
current->next = new_ptr;
41.
current = new_ptr;
42.

43.
current = start;
44.
printf("%s->\n ",new_ptr->letter);
45.
while(current != NULL)
46.
{
47.
printf("%s-> ",new_ptr->letter);
48.
current = current->next;
49.
}
50.
system("PAUSE");
51.
}

Recommended Answers

All 2 Replies

>is there a quicker way to fill the list with A,B,C,...,Y,Z whithout doing all this?
Yes, put your code to add a new node into a function, then use a loop:

int main()
{
  struct node *current = 0;
  const char *alphabet =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  for ( int i = 0; alphabet[i] != '\0'; i++ )
    current = add_node ( current, alphabet[i] );

  //...
}

This doesn't work....

const char *alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i=0;
do
{
            new_ptr = (struct node *)malloc(sizeof(struct node)); 
            new_ptr->next = NULL;   
            if (start == NULL) {    
                strcpy(new_ptr->letter, alphabet[i]);
                start = new_ptr;
                current = new_ptr;
            }
            else {      
                strcpy(new_ptr->letter, alphabet[i]);
                current->next = new_ptr;
                current = new_ptr;
            }
            //printf("***%s",*let);
            i++;
            //printf("***%s",*let);
        }while (alphabet[i] != '\0');
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.