public class Demo11 {
static class ListNode{
int val;
ListNode next;
ListNode(int x){val=x;}
}
public static ListNode reverse(ListNode head){
ListNode cur = head;
ListNode pre = null;
ListNode tmp;
while(cur!=null) {
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return head;
}
static void print(ListNode head){
while(head!=null){
System.out.println("节点"+head.val);
head = head.next;
}
}
public static void main(String[] args) {
ListNode f1 = new ListNode(1);
ListNode f2 = new ListNode(2);
ListNode f3 = new ListNode(3);
f1.next = f2;
f2.next = f3;
reverse(f1);
print(f1);
}
}
我以为调用reverse函数后,调用输出函数会输出3,2,1。但是只输出了1。然后我尝试输出f1.next发现
没有输出。