-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddNodeAtPosition.c++
71 lines (59 loc) · 1.22 KB
/
addNodeAtPosition.c++
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
#include<iostream>
using namespace std;
class Node{
public:
int val;
Node* next;
Node(int data){
val = data;
next = NULL;
}
};
void insertAtHead(Node* &head, int val){
Node* new_node = new Node(val);
new_node -> next = head;
head = new_node;
}
void insertAtTail(Node* &head, int val){
Node* new_node = new Node(val);
Node* temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = new_node;
}
void insertAtPosition(Node* &head, int val, int pos){
if(pos == 0){
insertAtHead(head, val);
return;
}
Node* new_node = new Node(val);
Node* temp = head;
int curr_pos = 0;
while(curr_pos != pos-1){
temp = temp->next;
curr_pos++;
}
new_node->next = temp->next;
temp->next = new_node;
}
void display(Node* head){
Node* temp = head;
while(temp!= NULL){
cout<<temp->val<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
int main(){
Node* head = NULL;
insertAtHead(head,2);
display(head);
insertAtHead(head,1);
display(head);
insertAtTail(head,3);
display(head);
insertAtPosition(head,4,1);
display(head);
return 0;
}