https://leetcode-cn.com/problems/reverse-linked-list/
object Solution {
/**
* 非递归方式
*/
def reverseList(head: ListNode): ListNode = {
if(head == null || head.next == null){
head
}else{
var prev = head
var cur = prev.next
head.next = null
while(cur != null){
val temp = cur.next
cur.next = prev
prev = cur
cur = temp
}
prev
}
}
/**
* 递归实现,相对循环更加难理解
*/
def reverseList(head:ListNode):ListNode={
if(head == null || head.next == null){
head
}else{
val res = reverseList(head.next)
head.next.next = head
head.next = null //特别注意:此处循环不需要
res
}
}
}
Scala实现单链表反转(leetCode 206)
反转链表:非递归与递归实现
最新推荐文章于 2022-03-29 14:16:29 发布
这篇文章详细介绍了如何使用非递归和递归方法解决LeetCode中的链表反转问题,展示了两种不同的实现方式并探讨了它们的优劣。
797

被折叠的 条评论
为什么被折叠?



