Leetcode - Reverse Linked List
Leetcode - Coin Change 2

Leetcode - Reverse Linked List II

violet posted @ Jun 06, 2020 04:29:25 AM in 算法 with tags Algorithm Golang Linked List , 294 阅读

https://leetcode.com/problems/reverse-linked-list-ii/

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

 

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseBetween(head *ListNode, m int, n int) *ListNode {
    if m == n {
        return head
    }
    count := 1
    node := head
    var head1 *ListNode
    for node != nil && count != m {
        count++
        head1 = node
        node = node.Next
    }
    if node == nil {
        return head
    }
    tail1 := node
    var prev2 *ListNode
    for node != nil {
        count++
        tmp := node.Next
        node.Next = prev2
        prev2 = node
        node = tmp
        if count == n {
            tmp := node.Next
            node.Next = prev2
            prev2 = node
            node = tmp
            break
        }
    }
    tail1.Next = node
    if head1 != nil {
        head1.Next = prev2
    } else {
        return prev2
    }
    
    
    return head
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter