添加 problem 25

This commit is contained in:
YDZ
2018-04-18 07:06:34 +08:00
parent b04dac0c24
commit 016ed2d20a
3 changed files with 112 additions and 0 deletions

View File

@ -0,0 +1,26 @@
# [25. Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/)
## 题目
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.
## 题目大意
这一题是 problem 24 的加强版problem 24 是两两相邻的元素,翻转链表。而 problem 25 要求的是 k 个相邻的元素翻转链表problem 相当于是 k = 2 的特殊情况。

View File

@ -0,0 +1,32 @@
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
node := head
for i := 0; i < k; i++ {
if node == nil {
return head
}
node = node.Next
}
newHead := reverse(head, node)
head.Next = reverseKGroup(node, k)
return newHead
}
func reverse(first *ListNode, last *ListNode) *ListNode {
prev := last
for first != last {
tmp := first.Next
first.Next = prev
prev = first
first = tmp
}
return prev
}

View File

@ -0,0 +1,54 @@
package leetcode
import (
"fmt"
"testing"
)
type question25 struct {
para25
ans25
}
// para 是参数
// one 代表第一个参数
type para25 struct {
one []int
two int
}
// ans 是答案
// one 代表第一个答案
type ans25 struct {
one []int
}
func Test_Problem25(t *testing.T) {
qs := []question25{
question25{
para25{
[]int{1, 2, 3, 4, 5},
3,
},
ans25{[]int{3, 2, 1, 4, 5}},
},
question25{
para25{
[]int{1, 2, 3, 4, 5},
1,
},
ans25{[]int{1, 2, 3, 4, 5}},
},
}
fmt.Printf("------------------------Leetcode Problem 25------------------------\n")
for _, q := range qs {
_, p := q.ans25, q.para25
fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(reverseKGroup(S2l(p.one), p.two)))
}
fmt.Printf("\n\n\n")
}