File tree Expand file tree Collapse file tree 4 files changed +61
-7
lines changed Top Open diff view settings Expand file tree Collapse file tree 4 files changed +61
-7
lines changed Top Open diff view settings Original file line number Diff line number Diff line change 1-
2-
31const LinkedList = require ( './linkedlist' ) ;
42
3+ // 2.3
4+
55LinkedList . prototype . deleteMiddleNode = deleteNode ;
66
77let list , node ;
Original file line number Diff line number Diff line change 1- class Node {
2- constructor ( data ) {
3- this . data = data ;
4- }
5- }
1+ const Node = require ( './node' ) ;
62
73class LinkedList {
84 constructor ( ) {
Original file line number Diff line number Diff line change 1+ class Node {
2+ constructor ( data ) {
3+ this . data = data ;
4+ }
5+ }
6+
7+ module . exports = Node ;
Original file line number Diff line number Diff line change 1+ const LinkedList = require ( './linkedlist' ) ;
2+ const Node = require ( './node' ) ;
3+
4+ LinkedList . prototype . partition = partition ;
5+
6+ function partition ( value ) {
7+ let left = null , right = null ;
8+
9+ // partition list
10+ for ( let current = this . head ; current ; current = current . next ) {
11+ const copy = new Node ( current . data ) ;
12+ if ( current . data < value ) {
13+ left = append ( left , copy ) ;
14+ } else {
15+ right = append ( right , copy ) ;
16+ }
17+ }
18+
19+ // merge list
20+ let lastLeft ;
21+ for ( lastLeft = left ; lastLeft . next ; lastLeft = lastLeft . next ) { }
22+ lastLeft . next = right ;
23+ this . head = left ;
24+ }
25+
26+
27+ function append ( head , node ) {
28+ if ( head ) { node . next = head ; }
29+ return node ;
30+ }
31+
32+ // testing
33+
34+ function test ( ) {
35+ const list = new LinkedList ( ) ;
36+ list . add ( 1 ) ;
37+ list . add ( 2 ) ;
38+ list . add ( 10 ) ;
39+ list . add ( 5 ) ;
40+ list . add ( 8 ) ;
41+ list . add ( 5 ) ;
42+ list . add ( 3 ) ;
43+
44+ console . log ( list . toString ( ) ) ; // 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1
45+
46+ list . partition ( 5 ) ;
47+
48+ console . log ( list . toString ( ) ) ; // 1 -> 2 -> 3 -> 10 -> 5 -> 8 -> 5
49+ }
50+
51+ test ( ) ;
You can’t perform that action at this time.
0 commit comments