-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertbeforenodedll.cpp
More file actions
64 lines (49 loc) · 1.13 KB
/
insertbeforenodedll.cpp
File metadata and controls
64 lines (49 loc) · 1.13 KB
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
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int data;
Node* next;
Node* back;
Node(int data1, Node* next1 = nullptr, Node* back1 = nullptr) {
data = data1;
next = next1;
back = back1;
}
};
// Build DLL from vector
Node* dll(vector<int>& arr) {
if (arr.empty()) return nullptr;
Node* head = new Node(arr[0]);
Node* prev = head;
for (int i = 1; i < arr.size(); i++) {
Node* temp = new Node(arr[i], nullptr, prev);
prev->next = temp;
prev = temp;
}
return head;
}
Node* insertNode(Node* node , int val){
Node* prev = node->back ;
Node* newNode = new Node(val , node , prev);
prev->next = newNode ;
node->back = newNode ;
}
// Print DLL
void printll(Node* head) {
while (head != nullptr) {
cout << head->data << " <-> ";
head = head->next;
}
cout << "NULL" << endl;
}
// Main function
int main() {
vector<int> arr = {12, 78, 56, 13};
Node* head = dll(arr);
int val = 5;
head = insertNode(head->next ,34); // capture new head
printll(head);
return 0;
}