File tree Expand file tree Collapse file tree 2 files changed +89
-0
lines changed Expand file tree Collapse file tree 2 files changed +89
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * function ListNode(val, next) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.next = (next===undefined ? null : next)
6
+ * }
7
+ */
8
+ /**
9
+ * @param {ListNode } head
10
+ * @return {ListNode }
11
+ */
12
+
13
+ // Declare linked list
14
+ function ListNode ( val ) {
15
+ this . val = val ;
16
+ this . next = null ;
17
+ }
18
+
19
+ var reverseList = function ( head ) {
20
+ let prev = null ;
21
+ let curr = head ;
22
+ let next ;
23
+
24
+ while ( curr !== null ) {
25
+ next = curr . next ;
26
+ curr . next = prev ;
27
+ prev = curr ;
28
+ curr = next ;
29
+ }
30
+ return prev ;
31
+ } ;
32
+
33
+ // Create liked list nodes
34
+ const node1 = new ListNode ( 1 ) ;
35
+ const node2 = new ListNode ( 2 ) ;
36
+ const node3 = new ListNode ( 3 ) ;
37
+ const node4 = new ListNode ( 4 ) ;
38
+ const node5 = new ListNode ( 5 ) ;
39
+
40
+ node1 . next = node2 ;
41
+ node2 . next = node3 ;
42
+ node3 . next = node4 ;
43
+ node4 . next = node5 ;
44
+
45
+ // Print out linked list
46
+ let current = node1 ;
47
+ while ( current !== null ) {
48
+ console . log ( current . val ) ;
49
+ current = current . next ;
50
+ }
51
+
52
+ // Reversed linked list
53
+ const reversedHead = reverseList ( node1 ) ;
54
+
55
+ // Print out reversed linked list
56
+ current = reversedHead ;
57
+ while ( current !== null ) {
58
+ console . log ( current . val ) ;
59
+ current = current . next ;
60
+ }
61
+
62
+ // TC: O(n)
63
+ // SC: O(1)
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s
3
+ * @return {boolean }
4
+ */
5
+ var isValid = function ( s ) {
6
+ // Create stack array
7
+ let stack = [ ] ;
8
+ // Iterate string to find there is an open bracket
9
+ for ( char of s ) {
10
+ // If it is an open bracket, push the close bracket into stack array
11
+ if ( char === "(" ) stack . push ( ")" ) ;
12
+ else if ( char === "{" ) stack . push ( "}" ) ;
13
+ else if ( char === "[" ) stack . push ( "]" ) ;
14
+ // If it is not an open bracket, compare last element of stack array
15
+ else if ( char !== stack . pop ( ) ) return false ;
16
+ }
17
+ // Check stack array still has any element after iteration
18
+ return stack . length === 0 ;
19
+ } ;
20
+
21
+ // TC: O(n)
22
+ // MC: O(n)
23
+
24
+ console . log ( isValid ( "()" ) ) ; //true
25
+ console . log ( isValid ( "()[]{}" ) ) ; //true
26
+ console . log ( isValid ( "([)]" ) ) ; //false
You can’t perform that action at this time.
0 commit comments