LeetCode - #61 Rotating linked list

Get into the habit of writing together! This is the sixth day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

foreword

Our community will successively organize Gu Yi ( Netflix growth hacker, author of "The Way of the iOS Interview", ACE professional fitness coach. )'s Swift algorithm problem solutions into a text version for everyone to learn and read.

We have updated the LeetCode algorithm for 61 issues so far, and we will keep the update time and progress ( released at 9:00 am on Monday, Wednesday, and Friday ). There will be a big improvement.

If you don't accumulate a small step, you can't go a thousand miles; if you don't accumulate a small stream, you can't make a river. The Swift community accompanies you to move forward. If you have suggestions and comments, please leave a message at the end of the article, we will try our best to meet your needs.

Difficulty Level: Difficult

1. Description

You are given the head node of a linked list head, rotate the linked list, and move keach positions.

2. Example

Example 1

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
复制代码

Example 2

输入:head = [0,1,2], k = 4
输出:[2,0,1]
复制代码

Restrictions:

  • The number of nodes in the linked list is in [0, 500]range
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

3. Answers

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class RotateList {
    func rotateRight(head: ListNode?, _ k: Int) -> ListNode? {
        if head == nil {
            return head
        }
    
        var prev = head
        var post = head
        let len = _getLength(head)
        var k = k % len
        
        while k > 0 {
            post = post!.next
            k -= 1
        }
        
        while post!.next != nil {
            prev = prev!.next
            post = post!.next
        }
        
        post!.next = head
        post = prev!.next
        prev!.next = nil
        
        return post
    }
    
    private func _getLength(head: ListNode?) -> Int {
        var len = 0
        var node = head
        
        while node != nil {
            len += 1
            node = node!.next
        }
        
        return len
    }
}
复制代码
  • Main idea: Runner Tech.
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Repository for the algorithm solution: LeetCode-Swift

Click to go to LeetCode practice

about us

We are jointly maintained by Swift enthusiasts. We will share the technical content centered on Swift combat, SwiftUI, and Swift foundation, and also organize and collect excellent learning materials.

Guess you like

Origin juejin.im/post/7084435902625234957