Linked List Class –
class MyList{
int val;
MyList next;
MyList(int val){
this.val = val;
}
@Override
public String toString() {
MyList current = this;
String out="";
while(current != null){
out += current.val+"-->";
current = current.next;
}
return out+"TAIL";
}
}
I tried and its working-
MyList list3 = list;
MyList list4 = list.next;
while(list3!=null && list4!=null){
alternateListswap(list3,list4);
if(list3.next.next==null || list4.next.next==null)
break;
list3 = (list3.next.next==null)?null:list3.next.next;
list4 = (list4.next.next==null)?null:list4.next.next;
}
private static MyList alternateListswap(MyList L3, MyList L4) {
int temp = L4.val;
L4.val = L3.val;
L3.val = temp;
return L3;
}
My Input –
MyList list = new MyList(1);
list.next = new MyList(2);
list.next.next = new MyList(3);
list.next.next.next = new MyList(4);
list.next.next.next.next = new MyList(5);
list.next.next.next.next.next = new MyList(6);
list.next.next.next.next.next.next = new MyList(7);
list.next.next.next.next.next.next.next = new MyList(8);
list.next.next.next.next.next.next.next.next = new MyList(9);
list.next.next.next.next.next.next.next.next.next = new MyList(10);
My list output is – 1–>2–>3–>4–>5–>6–>7–>8–>9–>10–>TAIL
Now I want to swap the alternate nodes in the LinkedList in JAVA.
EXPETED OUTPUT – 2–>1–>4–>3–>6–>5–>8–>7–>10–>9–>TAIL
You need to swap two elements (if there are at least two in the list) then proceed to the next pair.
Your approach currently does this: 1) go to the very end of the list (via front-recursion), then 2) swap elements as you go toward the front of the list (as you go up the recursive call chain). The result of this is to reverse the list
You need something like this: 1) if there are at least two elements in the list (
L,L.nextare valid) swap the two elements, then 2) proceed two eleemnts further and repeat (e.g.alternateListswap(L.next.next);)