-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse.js
130 lines (121 loc) · 3.33 KB
/
Reverse.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class Node{//here the node is creating
constructor(value){
this.value=value
this.next=null
}
}
class LinkedList{ //in here the the operations for the nodes(linkedlist) (eg.insert,delete)
constructor(){
this.head = null
this.size = 0
}
isEmpty(){
return this.size===0
}
getSize(){
return this.size
} //0(1)
prepend(value){
const TheNode = new Node(value)
if(this.isEmpty()){
this.head=TheNode
}else{
TheNode.next=this.head
this.head=TheNode
}
this.size++
}
insert(value, index) {
if (index < 0 || index > this.size) {
return;
}
const TheNode = new Node(value);
if (index === 0) {
this.prepend(value);
} else {
let previous = this.head;
for (let i = 0; i < index - 1; i++) {
previous = previous.next;
}
TheNode.next = previous.next;
previous.next = TheNode;
this.size++;
}
// Remove the problematic console.log
}
search(value){//this is the index searchin method inside the linkedlist
if(this.isEmpty()){
return -1
}
let i=0
let curr =this.head
while(curr){
if(curr.value==value){
return i
}
curr=curr.next
i++
}
return -1
}
reverse(value){
let prev= null
let curr =this.head
while(curr){
let next=curr.next
curr.next=prev
prev=curr
curr=next
}
this.head=prev
}
removeByValue(value) {
if (this.isEmpty()) {
return null;
}
if (this.head.value === value) {
this.head = this.head.next;
this.size--;
return value;
} else {
let prev = this.head;
while (prev.next && prev.next.value !== value) {
prev = prev.next;
}
if (prev.next) {//from here the value is deleting by the value that is passing
let removeNode = prev.next;
prev.next = removeNode.next;
this.size--;
return value;
}
return null;
}
}
print(){
if(this.isEmpty()){
console.log('list is empty')
}else{
let current = this.head
while(current){
console.log('List values are:',current.value)
current=current.next;
}
}
}
};
const TheList = new LinkedList()
console.log("empty or not check:",TheList.isEmpty());
console.log('list size:',TheList.getSize());//here is printing without any element in list
TheList.insert(10,0)
TheList.insert(20,1)
TheList.insert(30,2)
TheList.insert(100,3)
TheList.print()
console.log('---last---')
// console.log('list were',TheList.removeByValue(100))//in here the value is passing
console.log('.....After search the value.....')
console.log('Search:',TheList.search(30))//* this is the method for search by the element,
TheList.print() // and getting the index
console.log('After reverse')
TheList.reverse()
console.log(TheList.print() )