92. 反转链表 II
This commit is contained in:
@@ -2,49 +2,77 @@ package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func isMapEqual(a map[uint8]int, b map[uint8]int) bool {
|
||||
for k, v := range a {
|
||||
if val, ok := b[k]; ok {
|
||||
if val != v {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for k, v := range b {
|
||||
if val, ok := a[k]; ok {
|
||||
if val != v {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
/**
|
||||
* Definition for singly-linked list.*/
|
||||
type ListNode struct {
|
||||
Val int
|
||||
Next *ListNode
|
||||
}
|
||||
func checkStrings(s1 string, s2 string) bool {
|
||||
mp1 := make(map[uint8]int)
|
||||
mp2 := make(map[uint8]int)
|
||||
for i := 0; i < len(s1); i += 2 {
|
||||
mp1[s1[i]]++
|
||||
mp2[s2[i]]++
|
||||
|
||||
func makeLink(arr []int) *ListNode {
|
||||
if len(arr) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !isMapEqual(mp1, mp2) {
|
||||
return false
|
||||
head := &ListNode{}
|
||||
cur := head
|
||||
for _, v := range arr {
|
||||
cur.Next = &ListNode{Val: v}
|
||||
cur = cur.Next
|
||||
}
|
||||
mp1 = make(map[uint8]int)
|
||||
mp2 = make(map[uint8]int)
|
||||
for i := 1; i < len(s1); i += 2 {
|
||||
mp1[s1[i]]++
|
||||
mp2[s2[i]]++
|
||||
return head.Next
|
||||
}
|
||||
func checkLink(head *ListNode) {
|
||||
for head != nil {
|
||||
fmt.Println(head.Val)
|
||||
head = head.Next
|
||||
}
|
||||
if !isMapEqual(mp1, mp2) {
|
||||
return false
|
||||
}
|
||||
|
||||
func reverseBetween(head *ListNode, left int, right int) *ListNode {
|
||||
if head.Next == nil {
|
||||
return head
|
||||
}
|
||||
return true
|
||||
left--
|
||||
right--
|
||||
cur_idx := 0
|
||||
cur := head
|
||||
var left_node *ListNode
|
||||
var left_pre_node *ListNode = nil
|
||||
_ = left_pre_node
|
||||
var last_node *ListNode = nil
|
||||
do_rev := false
|
||||
|
||||
for {
|
||||
if cur_idx == left {
|
||||
left_node = cur
|
||||
left_pre_node = last_node
|
||||
do_rev = true
|
||||
}
|
||||
next := cur.Next
|
||||
if do_rev {
|
||||
next = cur.Next
|
||||
cur.Next = last_node
|
||||
if cur_idx == right {
|
||||
left_node.Next = next
|
||||
if left_pre_node != nil {
|
||||
left_pre_node.Next = cur
|
||||
} else {
|
||||
head = cur
|
||||
}
|
||||
do_rev = false
|
||||
}
|
||||
}
|
||||
last_node = cur
|
||||
cur = next
|
||||
cur_idx++
|
||||
if cur == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return head
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Printf("%v", checkStrings("abcdba", "cabdab"))
|
||||
arr := []int{3, 5}
|
||||
checkLink(reverseBetween(makeLink(arr), 1, 2))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user