-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertll.cpp
More file actions
56 lines (46 loc) · 1.21 KB
/
insertll.cpp
File metadata and controls
56 lines (46 loc) · 1.21 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
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
class Node {
public:
int data;
Node* next;
// Constructor with both data and next node
Node(int data1, Node* next1) {
data = data1;
next = next1;
}
// Constructor with only data (assuming next is initially null)
Node(int data1) {
data = data1;
next = nullptr;
}
};
// Function to print the linked list
void printLL(Node* head) {
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Function to insert a new node at the head of the linked list
Node* insertHead(Node* head, int val) {
Node* temp = new Node(val, head);
return temp;
}
int main() {
// Sample array and value for insertion
vector<int> arr = {12, 8, 5, 7};
int val = 100;
// Creating a linked list with initial elements from the array
Node* head = new Node(arr[0]);
head->next = new Node(arr[1]);
head->next->next = new Node(arr[2]);
head->next->next->next = new Node(arr[3]);
// Inserting a new node at the head of the linked list
head = insertHead(head, val);
// Printing the linked list
printLL(head);
return 0;
}