反转链表的Java实现

1. 题目

反转链表,例如,原链表1-2-3-4-5,反转后为5-4-3-2-1。

2. 迭代法实现

private ListNode reverseList(ListNode head) {if(head == null || head.next == null){return head;}ListNode cur = head.next;head.next = null;while(cur != null){ListNode next = cur.next;cur.next = head;head = cur;cur = next;}return head;
}

3. 头插法实现

private static ListNode reverseList(ListNode head) {if(head == null || head.next == null){return head;}ListNode newHead = new ListNode(0);while(head != null){ListNode next = head.next;head.next = newHead.next;newHead.next = head;head = next;}return newHead.next;
}