关于go:链表反转和删除第N个节点链表golang

35次阅读

共计 658 个字符,预计需要花费 2 分钟才能阅读完成。

package main

import "fmt"

type ListNode struct {
    val  int
    Next *ListNode
}

// 链表反转
func reverseList(head *ListNode) *ListNode {
    var pre *ListNode
    cur := head
    for cur != nil {
        temp := cur.Next
        cur.Next = pre
        pre = cur
        cur = temp
    }
    return pre
}

// 删除倒数第 N 个节点链表
func removeNthFromEnd(head *ListNode, n int) *ListNode {nodes := make([]*ListNode, 3)
    dummy := &ListNode{0, head}
    for node := dummy; node != nil; node = node.Next {nodes = append(nodes, node)
    }
    prev := nodes[len(nodes)-1-n]
    prev.Next = prev.Next.Next
    return dummy.Next
}

func main() {
    list := &ListNode{
        val: 1,
        Next: &ListNode{
            val: 2,
            Next: &ListNode{
                val:  3,
                Next: nil,
            },
        },
    }
    //fmt.Println(reverseList(list))
    result := removeNthFromEnd(list, 1)
    for result != nil {fmt.Printf("%d->", result.val)
        result = result.Next
    }
}

正文完
 0