24. 反转链表

NowCoder

解题思路

递归

  1. public ListNode ReverseList(ListNode head) {
  2. if (head == null || head.next == null)
  3. return head;
  4. ListNode next = head.next;
  5. head.next = null;
  6. ListNode newHead = ReverseList(next);
  7. next.next = head;
  8. return newHead;
  9. }

迭代

使用头插法。

public ListNode ReverseList(ListNode head) {
    ListNode newList = new ListNode(-1);
    while (head != null) {
        ListNode next = head.next;
        head.next = newList.next;
        newList.next = head;
        head = next;
    }
    return newList.next;
}

24. 反转链表 - 图1