leetcode刷题笔记一百四十三题 重排链表
leetcode刷题笔记一百四十三题 重排链表
源地址:143. 重排链表
问题描述:
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
//整个思路分为三步
//1.使用快慢指针,找到中间结点
//2.后半链表倒叙
//3.合并链表
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def reorderList(head: ListNode): Unit = {
if (head != null) {
var slow = head
var fast = head
while (fast != null && fast.next != null){
fast = fast.next.next
slow = slow.next
}
var current = slow
var prev: ListNode = null
while (current != null) {
val next = current.next
current.next = prev
prev = current
current = next
}
current = head
while (prev.next != null) {
val tmp1 = current.next
current.next = prev
current = tmp1
val tmp2 = prev.next
prev.next = current
prev = tmp2
}
}
}
}