美文网首页
删除重复链表

删除重复链表

作者: 将军红 | 来源:发表于2019-12-19 16:47 被阅读0次
    package main
    
    import "fmt"
    
    type Node struct {
        Next  *Node
        Value int
    }
    
    func initNode(items ...int) *Node {
        //return head
        if len(items) == 0 {
            return nil
        }
    
        Head := new(Node)
        node := Head
        for _, item := range items {
            node.Value = item
            node.Next = new(Node)
            node = node.Next
        }
        return Head
    }
    
    func printNode(node *Node) {
        fmt.Println("=============")
        for node.Next != nil {
            fmt.Println(node.Value)
            node = node.Next
        }
    }
    
    func deleteDumplicatedNode(p *Node) *Node {
        head := p
        if p == nil || p.Next == nil {
            return head
        }
    
        for p.Next != nil {
            pre := p
            step := p.Next
            for step.Next != nil {
                if p.Value == step.Value {
                    pre.Next = pre.Next.Next
                    step = step.Next
                } else {
                    pre = step
                    step = step.Next
                }
            }
            p = p.Next
        }
        return head
    }
    
    func main() {
        //node := initNode(3, 8, 3, 5, 7, 8)
        node := initNode(1, 1, 1, 2, 3)
        fmt.Println(node)
        printNode(node)
        newNode := deleteDumplicatedNode(node)
        printNode(newNode)
    }
    
    // 3,4,6,3,3,5,8
    

    相关文章

      网友评论

          本文标题:删除重复链表

          本文链接:https://www.haomeiwen.com/subject/gbxvnctx.html