Skip to content

Commit 9ff5e27

Browse files
authored
Merging question from Siddharth's repo.
2 parents b876e3d + 87b49cc commit 9ff5e27

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
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+
using namespace std;
42+
43+
struct node {
44+
int data;
45+
struct node *next;
46+
};
47+
48+
class list {
49+
node *head,*tail;
50+
public:
51+
list()
52+
{
53+
head=NULL;
54+
tail=NULL;
55+
}
56+
void insert(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+
void display()
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+
void insertbeg(int value){
82+
node *temp=new node;
83+
temp->data=value;
84+
temp->next=head;
85+
head=temp;
86+
}
87+
88+
};
89+
90+
int main() {
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 */
104+
return 0;
105+
}

0 commit comments

Comments
 (0)