File tree 2 files changed +86
-6
lines changed
2 files changed +86
-6
lines changed Original file line number Diff line number Diff line change @@ -140,13 +140,21 @@ class LinkedListNode {
140
140
141
141
Below are the types of LinkedList:
142
142
143
- ** Singly Linked List**
143
+ - ** Singly Linked List**
144
+ - ** Doubly Linked List**
145
+ - ** Circular Linked List**
144
146
145
- ![ ] ( https://i.imgur.com/byjRY7x.png )
147
+ ![ ] ( https://i.imgur.com/byjRY7x.png )
146
148
147
- ** Doubly Linked List **
149
+ #### Insert at head
148
150
149
- ** Circular Linked List**
151
+ The newly created node will become head of the linked list. · Size of the list is increased by one.
152
+
153
+ ![ ] ( https://i.imgur.com/79qwSqL.png )
154
+
155
+ #### Insert at tail
156
+
157
+ ![ ] ( https://i.imgur.com/Wz9Uovq.png )
150
158
151
159
### Stack
152
160
Original file line number Diff line number Diff line change @@ -6,5 +6,77 @@ class LinkedListNode {
6
6
}
7
7
8
8
class LinkedList {
9
-
10
- }
9
+ constructor ( ) {
10
+ this . head = null ;
11
+ this . length = 0 ;
12
+ }
13
+
14
+ insertAtHead ( value ) {
15
+ var newNode = new LinkedListNode ( value ) ;
16
+ newNode . next = this . head ;
17
+ this . head = newNode ;
18
+ this . length ++ ;
19
+
20
+ return newNode ;
21
+ }
22
+
23
+ insertAtTail ( value ) {
24
+ var newNode = new LinkedListNode ( value ) ;
25
+ let head = this . head ;
26
+
27
+ if ( ! head ) {
28
+ head = newNode ;
29
+ this . length ++ ;
30
+
31
+ return newNode ;
32
+ }
33
+
34
+ let temp = head ;
35
+
36
+ while ( temp . next ) {
37
+ temp = temp . next ;
38
+ }
39
+
40
+ // temp is tail
41
+ temp . next = newNode ;
42
+
43
+ this . length ++ ;
44
+
45
+ return newNode ;
46
+ }
47
+
48
+ toString ( ) {
49
+ if ( ! this . head ) {
50
+ return '' ;
51
+ }
52
+
53
+ let temp = this . head ;
54
+ let data = '' ;
55
+
56
+ while ( temp ) {
57
+ data += ',' + temp . data ;
58
+ temp = temp . next ;
59
+ }
60
+
61
+ return data . substr ( 1 , data . length ) ;
62
+ }
63
+ }
64
+
65
+ function createRandomLinkedList ( length ) {
66
+ const list = new LinkedList ( ) ;
67
+ for ( let i = 0 ; i < length ; i ++ ) {
68
+ list . insertAtHead ( Math . floor ( Math . random ( ) * 100 + 1 ) ) ;
69
+ }
70
+
71
+ return list ;
72
+ }
73
+
74
+ // Test-----------------------
75
+ const list = new LinkedList ( ) ;
76
+ list . insertAtHead ( 2 ) ;
77
+ console . log ( list . toString ( ) ) ;
78
+
79
+ list . insertAtTail ( 5 ) ;
80
+ console . log ( list . toString ( ) ) ;
81
+
82
+ console . log ( createRandomLinkedList ( 20 ) . toString ( ) ) ;
You can’t perform that action at this time.
0 commit comments