mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 16:36:41 +08:00
39 lines
690 B
Go
39 lines
690 B
Go
package leetcode
|
|
|
|
import (
|
|
"github.com/halfrost/LeetCode-Go/structures"
|
|
)
|
|
|
|
// ListNode define
|
|
type ListNode = structures.ListNode
|
|
|
|
/**
|
|
* Definition for singly-linked list.
|
|
* type ListNode struct {
|
|
* Val int
|
|
* Next *ListNode
|
|
* }
|
|
*/
|
|
|
|
func reverseBetween(head *ListNode, m int, n int) *ListNode {
|
|
if head == nil || m >= n {
|
|
return head
|
|
}
|
|
newHead := &ListNode{Val: 0, Next: head}
|
|
pre := newHead
|
|
for count := 0; pre.Next != nil && count < m-1; count++ {
|
|
pre = pre.Next
|
|
}
|
|
if pre.Next == nil {
|
|
return head
|
|
}
|
|
cur := pre.Next
|
|
for i := 0; i < n-m; i++ {
|
|
tmp := pre.Next
|
|
pre.Next = cur.Next
|
|
cur.Next = cur.Next.Next
|
|
pre.Next.Next = tmp
|
|
}
|
|
return newHead.Next
|
|
}
|