24. 反转链表
优质
小牛编辑
192浏览
2023-12-01
解题思路
递归
// java public ListNode ReverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode next = head.next; head.next = null; ListNode newHead = ReverseList(next); next.next = head; return newHead; }
迭代
使用头插法。
// java 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; }