-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_structructures_linked_list.js
102 lines (84 loc) · 1.83 KB
/
data_structructures_linked_list.js
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
98
99
100
101
102
/**
* Node class to build the node of the linked list
*/
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// let head = new Node(0);
// let temp = new Node();
// temp = head;
// for(let i=1;i<10;i++){
// let newNode = new Node(i);
// temp.next = newNode;
// temp = newNode;
// }
// Function to add the element at the start
function addElementAtStart(head,element){
let newHead = new Node(element);
newHead.next = head;
head = newHead
return newHead;
}
// Function to add the node at the end
function append(head,element){
let newNode = new Node(element);
let temp = head;
if (head == null){
head = newNode;
return head;
}
while(temp.next !==null){
temp = temp.next;
}
temp.next = newNode;
newNode.next = null;
return head;
}
// Function to pop the last element
function popElement(head){
if (head == null){
console.log("Empty linked list received");
return 0;
}
let temp = head;
while(temp.next !== null){
temp = temp.next;
}
let element = temp.data;
temp.next = null;
return element;
}
// function to remove nth element
function removeNthelement(head,n){
let temp = head;
for(let i=0;i<n-1;i++){
temp = temp.next;
}
nextNode = temp.next;
temp.next = nextNode.next;
}
//Driver Code
let head = new Node(0);
for(let i=10;i>=0;i--){
head = addElementAtStart(head,i);
}
traverse(head)
removeNthelement(head,5);
traverse(head);
console.log(popElement(head));
class LinkedList{
constructor(data){
this.head = new Node(data);
}
// Function to traverse the linked list
traverse(head){
let temp = head;
for(let i=0;i<10;i++){
console.log(temp.data);
temp = temp.next;
}
}
}