Q061 Rotate List
Input: -> 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 2
Expected: -> 5 -> 6 -> 1 -> 2 -> 3 -> 4
1. traverse the list to get the length, save the oldEnd node
2. calculate k % length, to find the newEnd node by shift length - k % length - 1
3. newEnd->next should be the new head
4. make oldEnd->next = oldHead
5. newEnd->next = nil
Example solution:
https://github.com/Sylvia-YiyinShen/Algorithm/blob/master/TwoPointers/Q061RotateList.playground/Contents.swift
No comments:
Post a Comment