public class ReverseList {
class ListNode {
ListNode next;
E val;
public ListNode(E value) {
val = value;
next = null;
}
public ListNode(E value, ListNode<E> n) {
val = value;
next = n;
}
public void setNext(ListNode<E> n) {
next = n;
}
}
static ListNode reverseList(ListNode head){
if(head==null){
return null;
}
ListNode curNode = head;
ListNode preNode = null;
while(curNode!=null){
ListNode nextNode = curNode.next;
curNode.next=preNode;
preNode = curNode;
curNode = nextNode;
System.out.println("This is preNode: "+preNode.val);
}
return preNode;
}
public static void main(String[] args) {
ReverseList rl= new ReverseList();
ReverseList.ListNode head = rl.new ListNode(1);
for (int i = 2; i <= 5; i++) {
head.next = rl.new ListNode(i);
head.next = head.next.next;
}
ListNode ln = reverseList(head);
while(ln.next!=null) {
System.out.println(ln.val);
ln = ln.next;
}
}
curNode.next;可能是空值,交换之前要先判断。
第36、37句赋值有问题,应该定义个临时变量赋值,37句又赋成空指针了