leetcode刷题笔记九十二题 反转链表II
leetcode刷题笔记九十二题 反转链表II
源地址:92. 反转链表 II
问题描述:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
/**
本题较为简单,找到需要反转的cur位置与pre位置并保存,在(m to n)中进行反转,再将保存的cur和pre位置与反转后链表相连即可
*/
object Solution {
def reverseBetween(head: ListNode, m: Int, n: Int): ListNode = {
if(head == null || m == n) return head
var start = new ListNode(0)
start.next = head
var pre = start
for(i <- 1 to m-1){
pre = pre.next
}
var cur = pre.next
val mPre = pre
val mCur = cur
for(i <- m to n){
val next = cur.next
cur.next = pre
pre = cur
cur = next
}
mPre.next = pre
mCur.next = cur
return start.next
}
}