1721. Swapping Nodes in a Linked List
package LeetCode_1721 /** * 1721. Swapping Nodes in a Linked List * https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ * You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] Example 2: Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 Output: [7,9,6,6,8,7,3,0,9,5] Example 3: Input: head = [1], k = 1 Output: [1] Example 4: Input: head = [1,2], k = 1 Output: [2,1] Example 5: Input: head = [1,2,3], k = 2 Output: [1,2,3] Constraints: 1. The number of nodes in the list is n. 2. 1 <= k <= n <= 105 3. 0 <= Node.val <= 100 * */ class ListNode(var `val`: Int) { var next: ListNode? = null } class Solution { /* * solution 1: change Linked List to array, return result Linked List after swap array, Time:O(n), Space:O(n); * solution 2: find out k-th from start and from end, swap both, Time:O(n), Space:O(1); * */ fun swapNodes(head: ListNode?, k: Int): ListNode? { //solution 1: var head_ = head var length = 0 while (head_ != null) { length++ head_ = head_.next } if (k == 1 && length == k) { return head } val reverseK = length - k val array = IntArray(length) head_ = head var i = 0 while (head_ != null) { array[i++] = head_.`val` head_ = head_.next } swap(array, k - 1, reverseK) val dummy = ListNode(-1) var head2 = dummy for (item in array) { head2.next = ListNode(item) head2 = head2.next!! } return dummy.next } private fun swap(nums: IntArray, i: Int, j: Int) { val temp = nums[i] nums[i] = nums[j] nums[j] = temp } }
solution 2
fun swapNodes(head: ListNode?, k: Int): ListNode? { //solution 2 var kNodeFromStart = head var kNodeFromEnd = head var current = head //find out k-th node from start for (i in 0 until k - 1) { current = current!!.next } kNodeFromStart = current //find out k-th node from end while (current!!.next != null) { /* * kNodeFromEnd is start from 0, so if current.next reach the end, kNodeFromEnd is at k-th start from end * */ kNodeFromEnd = kNodeFromEnd!!.next current = current.next } //swap val temp = kNodeFromStart!!.`val` kNodeFromStart!!.`val` = kNodeFromEnd!!.`val` kNodeFromEnd!!.`val` = temp return head }
标签:
LinkedList
, leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)