有關於交換節點的程式
利用 excElement(ListNode list, int i, int j)
ij 為要交換的元素順序
不過在執行中卻得到例外
Exception in thread "main" java.lang.NullPointerException
at Lab37.excElement(Lab37.java:92)
at Lab37.main(Lab37.java:22)
我的函式的行為是分成: 第一個節點
最後一個節點
同時第一個節點跟最後節點互換
跟以上皆非
錯誤在exeElement函式
請問我有邏輯錯誤嗎
麻煩大家 謝謝
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);
ListNode list = creatLinkedList();
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;
}
}
public static ListNode creatLinkedList() {
Scanner input = new Scanner(System.in);
ListNode cPtr = null;
ListNode fPtr = null;
System.out.print("Input the LinkedList's length :");
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;
}
}