LinkedList - 25. Reverse Nodes in k-Group

Updated on with 0 views and 0 comments
1. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

Example:

Given this linked list: `1->2->3->4->5`

For k = 2, you should return: `2->1->4->3->5`

For k = 3, you should return: `3->2->1->4->5`

Note:

• Only constant extra memory is allowed.
• You may not alter the values in the list's nodes, only nodes itself may be changed.

golang:

``````/**
* type ListNode struct {
*     Val int
*     Next *ListNode
* }
*/
// 递归求解，递归出口是找到翻转后的链表的头节点返回给外层调用
func reverseKGroup(head *ListNode, k int) *ListNode {
}

var size = 0
for cur != nil && size < k {
cur = cur.Next
size++
}

if size == k {
for size > 0 {
size--
}
}

}

// 使用数组存储链表值来翻转
func reverseKGroup2(head *ListNode, k int) *ListNode {
}

var counter = 0
var arr = make([]int, k)
for cur != nil {
if counter == 0 {
start = cur
}
// 记录需要翻转的值
arr[counter] = cur.Val
counter++

if counter == k {
for i := len(arr) - 1; i >= 0; i-- {
start.Val = arr[i]
start = start.Next
}
counter = 0
}
cur = cur.Next
}