Skip to content

Instantly share code, notes, and snippets.

@robtimp
Created March 13, 2018 17:49
Show Gist options
  • Save robtimp/67f0b545e677cb6ed04dc3c1b419085a to your computer and use it in GitHub Desktop.
Save robtimp/67f0b545e677cb6ed04dc3c1b419085a to your computer and use it in GitHub Desktop.
Reverse linked list nodes in groups of K length
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
var count = 0
var current = head
var previous: ListNode?
var newHead: ListNode?
while current != nil {
count += 1
current = current?.next
}
current = head
for _ in 0 ..< (count / k) {
let startOfGroup = reverseGroup(start: current, count: k)
if newHead == nil {
newHead = startOfGroup
}
previous?.next = startOfGroup
previous = current
current = current?.next
}
return newHead ?? head
}
func reverseGroup(start: ListNode?, count: Int) -> ListNode? {
var current = start
var previous: ListNode?
var next: ListNode?
for _ in 1...count {
next = current?.next
current?.next = previous
previous = current
current = next
}
start?.next = current
return previous
}
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int, next: ListNode? = nil) {
self.val = val
self.next = next
}
}
extension ListNode: CustomStringConvertible {
public var description: String {
let description = "\(val) -> "
if let next = next {
return description + next.description
} else {
return description + "nil"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment