File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Data Structures/Linked Lists/Singly Linked List Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Problem Statement:
2
+ //
3
+ // Given an linked list and we have to add a node at the beginning of linked list.
4
+ // The new node will be added at the beginning of a linked list.
5
+ //
6
+ // Example:
7
+ // Suppose we have an linked list : 50 -> 60
8
+ // Now insert(10)
9
+ // After insertion : 10 -> 50 -> 60
10
+
11
+ // Solution:
12
+ // step 1. Create a new node for the value that has to be inserted and assign value to it.
13
+ // step 2. now point the pointer of new node to the head of singly linked list.
14
+ // step 3: make the new node as our head.
15
+
16
+ // as we are doing constant operation
17
+ // Time complexity --> O( 1 )
18
+ // Space complexity --> O(1)
19
+
20
+ #include < iostream>
21
+ #include < bits/stdc++.h>
22
+ using namespace std ;
23
+
24
+ class node {
25
+
26
+ public:
27
+ int data;
28
+ node *next;
29
+
30
+ node (int x){
31
+ data=x;
32
+ next=NULL ;
33
+ }
34
+ };
35
+
36
+ node *insertBegin (node *head, int x)
37
+ {
38
+ node *temp = new node (x); // create a new node as temp for the value
39
+ temp->next =head; // making temp next as our head
40
+ return temp; // finally return
41
+ }
42
+
43
+ void display (node *head){
44
+
45
+ node *curr=head;
46
+ while (curr!=NULL )
47
+ {
48
+ cout<<curr->data <<" " ;
49
+ curr=curr->next ;
50
+ }
51
+ }
52
+
53
+ int main ()
54
+ {
55
+ node *head = new node (50 );
56
+ head->next = new node (60 );
57
+ cout<<" Linked list before inserting: " ;
58
+ display (head);
59
+ cout<<endl;
60
+ head = insertBegin (head, 10 );
61
+ cout<<" Linked list after inserting at the beginning: " ;
62
+ display (head);
63
+
64
+
65
+ }
You can’t perform that action at this time.
0 commit comments