0

## JAVA節點交換 問題

ij 為要交換的元素順序

at Lab37.excElement(Lab37.java:92)
at Lab37.main(Lab37.java:22)

``````import java.util.*;
import java.io.*;

class ListNode {
int value;
ListNode nextNode = null;
public ListNode(int value) {
this.value = value;
}
}

public class Lab37 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Input the position of first element you want to exchange :");
int i = input.nextInt();
System.out.print("Input the position of second element you want to exchange :");
int j = input.nextInt();

ListNode afterExc = excElement(list, i, j);

while(afterExc != null) {
System.out.print(afterExc.value + " ");
afterExc = afterExc.nextNode;
}

}
Scanner input = new Scanner(System.in);
ListNode cPtr = null;
ListNode fPtr = null;

int length = input.nextInt();
int value;
for(int i = 0; i < length; i++) {
System.out.printf("Input the %d element's value :", i);
value = input.nextInt();
ListNode t;
if(i == 0) {
t = new ListNode(value);
cPtr = t;
fPtr = t;
}else{
t = new ListNode(value);
cPtr.nextNode = t;
cPtr = t;
}
}
return fPtr;
}
public static ListNode excElement(ListNode list, int i, int j) {
ListNode iNode = null;
ListNode jNode = null;
ListNode afterINode = null;
ListNode afterJNode = null;
ListNode beforeINode = null;
ListNode beforeJNode = null;

ListNode cPtr = list;

int length =0;

while(cPtr != null) {
length++;
cPtr = cPtr.nextNode;
}
cPtr = list;

for(int k = 1; k <= j + 1; k++) {
if(k == (i - 1)) {
beforeINode = cPtr;
}else if(k == i) {
iNode = cPtr;
}else if(k == (i + 1)) {
afterINode = cPtr;
}else if(k == (j - 1)) {
beforeJNode = cPtr;
}else if(k == j) {
jNode = cPtr;
}else if(k == (j + 1)) {
afterJNode = cPtr;
}
cPtr = cPtr.nextNode;
}

if(i == 1 && j != length) {
list = jNode;
jNode.nextNode = afterINode;
beforeJNode.nextNode = iNode;
iNode.nextNode = afterJNode;
}else if(i != 1 && j == length) {
beforeINode.nextNode = jNode;
jNode.nextNode = afterINode;
beforeJNode.nextNode = iNode;
iNode.nextNode = null;
}else if(i == 1 && j ==length) {
list = jNode;
jNode.nextNode = afterINode;
beforeJNode.nextNode = iNode;
iNode.nextNode = null;
}else {
beforeINode.nextNode = jNode;
jNode.nextNode = afterINode;
beforeJNode.nextNode = iNode;
iNode.nextNode = afterJNode;
}

return list;
}
}
``````