File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-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
+ var swapPairs = function ( head ) {
13
+ if ( head === null ) {
14
+ return null ;
15
+ }
16
+
17
+ let result = [ ] ;
18
+ let thisNode = head ;
19
+ while ( thisNode !== null ) {
20
+ result . push ( thisNode ) ;
21
+ thisNode = thisNode . next ;
22
+ }
23
+
24
+ for ( let i = 1 ; i < result . length ; i += 2 ) {
25
+ console . log ( "i" , i ) ;
26
+ let temp = result [ i - 1 ] ;
27
+ result [ i - 1 ] = result [ i ] ;
28
+ result [ i ] = temp ;
29
+ }
30
+
31
+ for ( let i = 0 ; i < result . length ; i ++ ) {
32
+ if ( i === result . length ) {
33
+ result [ i ] . next = null ;
34
+ } else {
35
+ result [ i ] . next = result [ i + 1 ] ;
36
+ }
37
+ }
38
+
39
+ return result [ 0 ] ;
40
+ } ;
41
+
42
+ function ListNode ( val , next ) {
43
+ this . val = val === undefined ? 0 : val ;
44
+ this . next = next === undefined ? null : next ;
45
+ }
46
+
47
+ f = new ListNode ( 9 ) ;
48
+ e = new ListNode ( 8 , f ) ;
49
+ d = new ListNode ( 7 , e ) ;
50
+ c = new ListNode ( 6 , d ) ;
51
+ b = new ListNode ( 5 , c ) ;
52
+ a = new ListNode ( 4 , b ) ;
53
+
54
+ console . log ( swapPairs ( a ) ) ;
You can’t perform that action at this time.
0 commit comments