leetcode刷题笔记 二百零六题 反转链表
leetcode刷题笔记 二百零六题 反转链表
源地址:206. 反转链表
问题描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
//迭代 头插法
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def reverseList(head: ListNode): ListNode = {
var prev: ListNode = null
var curr = head
while (curr != null) {
val temp = curr.next
curr.next = prev
prev = curr
curr = temp
}
return prev
}
}
//递归
// 。。。 -> k -> k+1 <- k+2 。。。
//故 k.next.next = k
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def reverseList(head: ListNode): ListNode = {
if (head == null || head.next == null) return head
val temp = reverseList(head.next)
head.next.next = head
head.next = null
return temp
}
}