这里默认不能修改节点中的值,不能新建新的链表来进行反转,反转链表只能在原单向链表上进行。具体代码如下所示:
public class ListNode{
public int value;
public ListNode next;
public ListNode(int value){
this.value = value;
}
}
public ListNode reverse(ListNode head){
if(head == null || head.next == null){
return root;
}
ListNode prev = null, cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}