You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Write a program to create a linked list with the given number of elements by inserting every element at the beginning.If there are no elements given then the head of the linked list will be null. After completing the insertion of all elements print the elements in the linked list at the end. If no elements are inserted then print null on the standard output.
3
+
4
+
Note: Intially the linked list will be empty
5
+
6
+
Input Format
7
+
8
+
First Line contains number of elements(n) to be inserted and followed the n elements
9
+
10
+
Constraints
11
+
12
+
0<=n<=100
13
+
14
+
1<=element<=10000
15
+
16
+
Output Format
17
+
18
+
Print the elements in the linkedlist
19
+
20
+
Sample Input 0
21
+
22
+
5
23
+
5
24
+
4
25
+
3
26
+
2
27
+
1
28
+
Sample Output 0
29
+
30
+
1->2->3->4->5
31
+
Explanation 0
32
+
33
+
Initially the list will be empty and then we will add 5. After that we will add 4 infront of 5. Similarly 3 infront of 4 and so on.
34
+
*/
35
+
36
+
#include<cmath>
37
+
#include<cstdio>
38
+
#include<vector>
39
+
#include<iostream>
40
+
#include<algorithm>
41
+
usingnamespacestd;
42
+
43
+
structnode {
44
+
int data;
45
+
structnode *next;
46
+
};
47
+
48
+
classlist {
49
+
node *head,*tail;
50
+
public:
51
+
list()
52
+
{
53
+
head=NULL;
54
+
tail=NULL;
55
+
}
56
+
voidinsert(int value){
57
+
node *temp=new node;
58
+
temp->data=value;
59
+
if(head==NULL)
60
+
{
61
+
head=temp;
62
+
tail=temp;
63
+
}
64
+
else
65
+
{
66
+
tail->next=temp;
67
+
tail=temp;
68
+
}
69
+
}
70
+
voiddisplay()
71
+
{
72
+
node *temp=new node;
73
+
temp=head;
74
+
while(temp->next!=NULL)
75
+
{
76
+
cout<<temp->data<<"->";
77
+
temp=temp->next;
78
+
}
79
+
cout<<temp->data;
80
+
}
81
+
voidinsertbeg(int value){
82
+
node *temp=new node;
83
+
temp->data=value;
84
+
temp->next=head;
85
+
head=temp;
86
+
}
87
+
88
+
};
89
+
90
+
intmain() {
91
+
int a,i;
92
+
cin>>a;
93
+
int b[a];
94
+
list l1;
95
+
cin>>b[0];
96
+
l1.insert(b[0]);
97
+
for(i=1; i<a; i++)
98
+
{
99
+
cin>>b[i];
100
+
l1.insertbeg(b[i]);
101
+
}
102
+
l1.display();
103
+
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
0 commit comments