已经是最新一篇文章了!
已经是最后一篇文章了!
24. 反转链表
四面歌残终破楚,八年风味徒思浙。
24. 反转链表
解题思路
递归
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;
}
迭代
使用头插法。
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;
}
版权声明:如无特别声明,本站收集的文章归原作者 cs-notes 所有。 如有侵权,请联系删除。
联系邮箱: GenshinTimeStamp@outlook.com
本文标题:《 24. 反转链表 》