Repository navigation
Expand file tree
/
Copy pathlinked_list.cpp
More file actions
95 lines (78 loc) · 1.88 KB
/
Copy pathlinked_list.cpp
File metadata and controls
95 lines (78 loc) · 1.88 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
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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
class LinkedList{
public:
Node* head;
};
void InsertAtTheFront(Node** head, int data){
// create a new node
Node* new_node = new Node();
// put the node at the front of the list
new_node->data = data;
new_node->next = *head;
// update the head to this new node
*head = new_node;
}
void InsertAtTheEnd(Node** head, int data){
// create a new node
Node* new_node = new Node();
new_node->data = data;
new_node->next = NULL;
// if the list is empty, make the new node the head
if(*head == NULL){
*head = new_node;
return;
}
// traverse to the end of the list
Node* temp = *head;
while(temp->next != NULL){
temp = temp->next;
}
// update the last node to point to the new node
temp->next = new_node;
}
void insertAfter(Node* previous, int data){
// check whether the previous node is NULL
if(previous == NULL){
cout << "The previous node cannot be NULL";
return;
}
// create a new node
Node* new_node = new Node();
new_node->data = data;
// update the new node to point to the next node
new_node->next = previous->next;
previous->next = new_node;
}
void print_List(Node* n){
Node* temp = n;
while(temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
}
int main(){
Node* head = new Node();
Node* Second = new Node();
Node* Third = new Node();
head->data = 1;
head->next = Second;
Second->data = 2;
Second->next = Third;
Third->data = 3;
Third->next = NULL;
InsertAtTheFront(&head, -1);
print_List(head);
cout << endl;
InsertAtTheEnd(&head, 4);
print_List(head);
cout << endl;
insertAfter(Second, -2235);
print_List(head);
return 0;
}