-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list4.c
More file actions
109 lines (87 loc) · 1.7 KB
/
linked_list4.c
File metadata and controls
109 lines (87 loc) · 1.7 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Develop a menu driven program to insert a node in the linked list and display the same. Based on the options given in the input, the corresponding subroutine should be executed. The options are as follows-
// option 1 - to insert a node in the beginning of the linked list
// option 2 - to insert a node in the end of the linked list.
// Input Format
// no. of nodes n
// next n lines denotes the values of the nodes
// option
// value of the node to insert
// Sample Input
// 4
// 55
// 33
// 44
// 22
// 1
// 88
// Sample Output
// 88
// 55
// 33
// 44
// 22
#include <stdio.h>
#include <stdlib.h>
struct node
{
int element;
struct node *next;
};
typedef struct node node;
void insertBeg(node *list, int x)
{
node *newnode = malloc(sizeof(node));
newnode->element = x;
newnode->next = list->next;
list->next = newnode;
}
void insertLast(node *list, int x)
{
node *newnode = malloc(sizeof(node));
newnode->element = x;
newnode->next = NULL;
node *pos = list;
while (pos->next != NULL)
{
pos = pos->next;
}
pos->next = newnode;
}
void traverse(node *list)
{
node *pos = list;
while (pos->next != NULL)
{
pos = pos->next;
printf("%d\n", pos->element);
}
}
int main()
{
int n;
scanf("%d", &n);
node *list = malloc(sizeof(node));
list->next = NULL;
while (n--)
{
int x;
scanf("%d", &x);
insertLast(list, x);
};
int ch;
scanf("%d", &ch);
if (ch == 1)
{
int t;
scanf("%d", &t);
insertBeg(list, t);
}
else
{
int t;
scanf("%d", &t);
insertLast(list, t);
}
traverse(list);
return 0;
}