Saturday, 31 August 2013

Singly Linked List swap not working

Singly Linked List swap not working

I have been trying for some time now to achieve to swap pointers of nodes
in a singly Linked List without a lot of success, so any help would be
totally acceptable ( I have already read and tried to use in my code a lot
of answers from previous questions but it seems that i am doing something
wrong..)
Here is the code:
public void implementation() {
count = new long[5];
for (int i = 0; i <= 4; i++) {
count[i] = count2++;
}
Link[] nodeList2 = LinkList.Insert_Link(count,count.length);
for (int i = 0; i < nodeList2.length - 1; i++) {
nodeList2[i].next = nodeList2[i + 1];
}
for (int i = 0; i < nodeList2.length - 1; i += 2) {
LinkList.Swap_Node_Pointers(nodeList2[i], nodeList2[i + 1]);
}
// LinkList.Swap_Node_Pointers(nodeList2[1],nodeList2[1+1]);
LinkList.display(nodeList2);
}
And the code of the Insert, Swap_Node_Points and display is:
public Link[] Insert_Link(long[] value, int countlength) {
final Link[] nodeList = new Link[countlength] ;
for (int i = 0; i < nodeList.length; i++) {
nodeList[i] = new Link();
nodeList[i].value2 = value[i];
}
return nodeList;
}
public void display(Link[] b) {
Link[] nodeList2 = b;
for (int i = 0; i < nodeList2.length; i++) {
System.out.println("The value is" +nodeList2[i].value2);
System.out.println("");
}
}
public void Swap_Node_Values( final Link n1, final Link n2) {
long value;
// Link temp = null;
value = n1.value2;
n1.value2 = n2.value2;
n2.value2 = value;
}
public void Swap_Node_Pointers(Link n1,Link n2) {
Link temp = n1.next;
n1.next = n2.next;
n2.next = temp;
}

No comments:

Post a Comment