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 发布