Skip to content

Commit ebfc4a2

Browse files
Create Singly_Linked_List -Program_2.c
1 parent 272b763 commit ebfc4a2

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

Singly_Linked_List -Program_2.c

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// In a goods train, all the wagons attached to the train have a sheet of paper pasted that tells how much is the total weight of the goods in each wagon. The first wagon is attached to the engine, the second wagon is attached to the first wagon and so on and the last one is guard van. Given the weights of goods in the wagon as input, print the weights in the reverse order.
2+
3+
// Example
4+
5+
// If the weights of the wagons starting from wagon 1 are as follows- 100->200->300->NULL then print the weights in the following order 300->200->100->NULL
6+
7+
// Input Format
8+
9+
// The first line contains an integer n, the number of elements in the linked list.
10+
// Each of the next n, lines contains an integer, the data values of the elements in the linked list.
11+
12+
// Constraints
13+
14+
// 1 <=n <= 1000
15+
16+
// 1 <= list[i] <= 1000, where list[i] is the ith element in the list.
17+
18+
// Sample Input
19+
20+
// 5
21+
// 1
22+
// 2
23+
// 3
24+
// 4
25+
// 5
26+
// Sample Output
27+
28+
// 5 4 3 2 1
29+
// Explanation
30+
31+
// The initial linked list is: 1->2->3->4->5
32+
33+
// The reversed linked list is: 5->4->3->2->1
34+
35+
#include<stdio.h>
36+
#include<stdlib.h>
37+
struct node
38+
{
39+
int element;
40+
struct node *next;
41+
struct node *prev;
42+
};
43+
typedef struct node node;
44+
node *position;
45+
void insert(node *list,int e)
46+
{
47+
node *newnode=malloc(sizeof(node));
48+
newnode->element=e;
49+
if(list->next==NULL)
50+
{
51+
list->next=newnode;
52+
newnode->prev=list;
53+
newnode->next=NULL;
54+
position=newnode;
55+
}
56+
else
57+
{
58+
newnode->next=NULL;
59+
position->next=newnode;
60+
newnode->prev=position;
61+
position=newnode;
62+
}
63+
}
64+
void display(node *list)
65+
{
66+
if(list->next!=NULL)
67+
{
68+
node *pos=position;
69+
while(pos->prev!=NULL)
70+
{
71+
printf("%d\n",pos->element);
72+
pos=pos->prev;
73+
}
74+
}
75+
}
76+
int main()
77+
{
78+
int n,m;
79+
node *list=malloc(sizeof(node));
80+
list->next=NULL;
81+
list->prev=NULL;
82+
scanf("%d",&n);
83+
for(int i=0;i<n;i++)
84+
{
85+
scanf("%d",&m);
86+
insert(list,m);
87+
}
88+
display(list);
89+
return 0;
90+
}

0 commit comments

Comments
 (0)