Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
pre始终是首元结点的值,每次对pnext重新赋值
递归
public ListNode reverseList(ListNode head) {
if(head == null ) return null;
if(head.next == null) return head;
ListNode p = head.next;
ListNode q = reverseList(p);
head.next = null;
p.next = head;
return q;
}
非递归
public ListNode reverseList1(ListNode head) {
if(head == null ) return null;
if(head.next == null) return head;
ListNode pre = head;
ListNode p = head.next;
head.next = null;
ListNode tmp ;
while(p!=null){
tmp = p.next;
p.next = pre;
pre = p;
p = tmp;
}
return pre;
}