-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insert at end of Doubly Linked List.cpp
97 lines (58 loc) · 1.54 KB
/
Insert at end of Doubly Linked List.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node* back;
Node(int data1, Node* next1, Node* back1) {
data = data1;
next = next1;
back = back1;
}
Node(int data1) {
data = data1;
next = nullptr;
back = nullptr;
}
};
Node* convertArr2DLL(vector<int> arr) {
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;
}
void print(Node* head) {
while (head != nullptr) {
cout << head->data << " ";
head = head->next;
}
}
Node* insertAtTail(Node* head, int k) {
Node* newNode = new Node(k);
if (head == nullptr) {
return newNode;
}
Node* tail = head;
while (tail->next != nullptr) {
tail = tail->next;
}
tail->next = newNode;
newNode->back = tail;
return head;
}
int main() {
vector<int> arr = {12, 5, 8, 7, 4};
Node* head = convertArr2DLL(arr);
cout << "Doubly Linked List Initially: " << endl;
print(head);
cout << endl << "Doubly Linked List After Inserting at the tail with value 10: " << endl;
head = insertAtTail(head, 10);
print(head);
return 0;
}