Reverse a singly linked list.
这道题可以用多种方法解决,最容易想到的就是利用栈,然后从新建立一个链表,这种方法空间复杂度较高;另外一种是通过递归的方式进行;
后来看到别人写的这种方法,自己没想到,感觉很不错!
public static ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode pre = head;
ListNode p = head.next;
pre.next = null;
ListNode nxt;
while(p != null) {
nxt = p.next;
p.next = pre;
pre = p;
p = nxt;
}
return pre;
}