-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq6_linked_list.c
68 lines (58 loc) · 1.4 KB
/
q6_linked_list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>
// A node structure for linked list
struct node
{
int data;
struct node *next;
};
void print_linked_list(struct node *node)
{
int i=0;
while(node!=NULL)
{
printf("Linked list %d: %d", i, node->data);
i++;
node = node->next;
}
}
int main(){
char input[5];
int intInput;
struct node *start=NULL, *current;
while(1)
{
// struct node new_node; will fail becoz its memory location is the same each and everytime in this whil..loop scope, we have to use malloc
struct node *new_node = malloc( sizeof(struct node) );; // assign a new node for each iteration
printf("\nPlease enter an integer to be stored (enter 'x' to exit): ");
scanf("%s", input);
if(strcmp(input,"x")==0) // Exit if x is entered
{
if(start!=NULL)
print_linked_list(start); // print the content of linked list
break;
}
intInput = atoi(input);
if(start==NULL)
{
start = new_node;
current = new_node;
start->data = intInput;
//printf("start->data: %d", start->data);
start->next = NULL;
}
else
{
if(current->next==NULL)
{
//printf("Inside");
current->next = new_node;
current = current->next;
}
current->data = intInput;
current->next = NULL;
//printf("current->data: %d", current->data);
}
}
return 0;
}