public class node {
int data ;
node next = null ;
//constructor
public node(int newdata){
data = newdata ;
next = null ;
}
//-----------------------------TROUBLE FUNCTION----------------
public void attach(int newdata){
node list = this ;
if(list.next == null)System.out.println("alas only 1 element given! last element so far " + list.data) ;
while(list.next != null){
System.out.println("---------------------------------------") ;
list = list.next ;
}
list.next = new node(newdata) ;
}
}
I m writing another function split()
that splits the list into 2 lists:
bigger_than int x
and less_than x
.
But initially these 2 lists are empty(bigger_than & less_than)
I m trying to attach to these 2 empty lists - this is the bug I can't resolve
public static void divide_list_around_x(int x, node list){
node less_than = null ;
node bigger_than = null ;
node current = list ;
while(current != null){
if( current.data < x){
//less_than is null here
less_than.attach(current.data);
}
else{
//bigger list is null
bigger_than.attach(current.data) ;
}
current = current.next ;
}
}
public static void main(String[] args) {
//creating list, attach 1 by 1
node first = new node( 4) ;
first.attach( 78) ;
first.attach( 5) ;
first.attach( 51) ;
first.attach( 157) ;
first.attach( 3) ;
divide_list_around_x(78,first) ;
}