Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
单链表反转
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
注意学习递归解法
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
如果输入是1->2->3->4
p=4
head=3
head.next.next = head;//4->3
head.next = null;//3不再指向4
循环下去 每次都让当前节点的下一个节点指向当前节点 让当前节点指向null 最后返回尾节点