-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08. Set in SLL.js
110 lines (99 loc) · 2.27 KB
/
08. Set in SLL.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
103
104
105
106
107
108
109
110
class Node{
constructor(val){
this.val = val;
this.next = null;
}
}
class SinglyLinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = null;
}
traverse(){
var currentVal = this.head
while(currentVal){
console.log(currentVal.val);
currentVal = currentVal.next;
}
}
push(val){
var newNode = new Node(val);
if(!this.head){
this.head = newNode;
this.tail = newNode;
}
else{
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
pop(){
let current = this.head;
let newtail = current;
if(!this.head){
return undefined;
}
else{
while(current.next){
newtail = current;
current = current.next;
}
}
this.tail = newtail;
this.tail.next = null;
this.length--;
if(this.length === 0){
this.head = null;
this.tail = null;
}
return current;
}
shift(){
if(!this.head) return undefined;
var currentHead= this.head ;
var newHead = this.head.next;
this.head = newHead;
this.length--;
return currentHead;
}
unshift(val){
var newNode = new Node(val);
if(!this.head){
this.head = newNode;
this.tail = newNode;
}
else{
var temp = this.head;
this.head = newNode;
this.head.next = temp;
console.log(temp.val);
}
this.length++;
return this;
}
get(index){
if(index<0||index>this.length) return null;
var current = this.head;
for(i=0;i<index;i++){
current = current.next
}
return current;
}
set(value,index){
let node = this.get(index);
if(node){
node.val = value;
}
return this;
}
}
var jist = new SinglyLinkedList()
jist.push("JHI");
jist.push("HI");
jist.push("I am arsh");
jist.push("How are you");
jist.push("I am fine");
jist.set("God",1)