24. 反转链表


文档摘要

反转链表 NowCoder 解题思路 递归 迭代 使用头插法。

24. 反转链表

NowCoder

解题思路

递归

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; }

作者与出处
原作者: CyC2018
来源:CyC2018
许可证:CC BY-NC-SA 4.0
整理: 灏天文库整理
由灏天文库结构化整理,提供目录导航、全文检索与在线阅读,便于系统化学习
发布者: 作者: CyC2018 转发
评论区 (0)
U