添加 problem 24

This commit is contained in:
YDZ
2018-04-17 11:54:28 +08:00
parent 9744b5ba67
commit b04dac0c24
3 changed files with 146 additions and 0 deletions

View File

@ -0,0 +1,17 @@
# [24. Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/description/)
## 题目
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
## 题目大意
两两相邻的元素,翻转链表

View File

@ -0,0 +1,38 @@
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
s := head.Next
var behind *ListNode
for head.Next != nil {
headNext := head.Next
if behind != nil && behind.Next != nil {
behind.Next = headNext
}
var next *ListNode
if head.Next.Next != nil {
next = head.Next.Next
}
if head.Next.Next != nil {
head.Next = next
} else {
head.Next = nil
}
headNext.Next = head
behind = head
if head.Next != nil {
head = next
}
}
return s
}

View File

@ -0,0 +1,91 @@
package leetcode
import (
"fmt"
"testing"
)
type question24 struct {
para24
ans24
}
// para 是参数
// one 代表第一个参数
type para24 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans24 struct {
one []int
}
func Test_Problem24(t *testing.T) {
qs := []question24{
question24{
para24{[]int{}},
ans24{[]int{}},
},
question24{
para24{[]int{1}},
ans24{[]int{1}},
},
question24{
para24{[]int{1, 2, 3, 4}},
ans24{[]int{2, 1, 4, 3}},
},
question24{
para24{[]int{1, 2, 3, 4, 5}},
ans24{[]int{2, 1, 4, 3, 5}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 24------------------------\n")
for _, q := range qs {
_, p := q.ans24, q.para24
fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(swapPairs(S2l(p.one))))
}
fmt.Printf("\n\n\n")
}
// convert *ListNode to []int
func L2s(head *ListNode) []int {
res := []int{}
for head != nil {
res = append(res, head.Val)
head = head.Next
}
return res
}
// convert []int to *ListNode
func S2l(nums []int) *ListNode {
if len(nums) == 0 {
return nil
}
res := &ListNode{
Val: nums[0],
}
temp := res
for i := 1; i < len(nums); i++ {
temp.Next = &ListNode{
Val: nums[i],
}
temp = temp.Next
}
return res
}