JZ76 删除链表中重复的结点

图片

我的实现

package main

import . "nc_tools"

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param pHead ListNode类
 * @return ListNode类
 */
func deleteDuplication(pHead *ListNode) *ListNode {
    if pHead == nil {
        return nil
    }
    next := pHead.Next
    cur := pHead
    head := &ListNode{0, cur}
    prev := head
    for next != nil {
        if cur.Val == next.Val || cur.Val == head.Val {
            head.Val = cur.Val
            prev.Next = next
        } else {
            prev = cur
        }
        cur = next
        next = next.Next
    }
    if cur.Val == head.Val {
        prev.Next = next
    }
    return head.Next
}

官方思路

0A01E83A481A4919FAE203E7BB77FDD3

package main

import . "nc_tools"

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param pHead ListNode类
 * @return ListNode类
 */
func deleteDuplication(pHead *ListNode) *ListNode {
    if pHead == nil {
        return nil
    }
    head := &ListNode{0, pHead}
    prev := head
    cur := prev.Next
    next := cur.Next
    for next != nil {
        if cur.Val == next.Val {
            next = next.Next
        } else if cur.Val == cur.Next.Val {
            cur = next
            next = next.Next
            prev.Next = cur
        } else {
            prev = cur
            cur = next
            next = next.Next
        }
    }
    if cur.Next != nil && cur.Val == cur.Next.Val {
        prev.Next = nil
    }
    return head.Next
}

JZ18 删除链表的节点

图片

package main

import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @param val int整型 
 * @return ListNode类
*/
func deleteNode(head *ListNode, val int) *ListNode {
    if head == nil {
        return nil
    }
    h := &ListNode{0, head}
    prev := h
    cur := h.Next
    for cur != nil {
        cur = cur.Next
        if prev.Next.Val == val {
            prev.Next = cur
        } else {
            prev = prev.Next
        }
    }
    return h.Next
}
文章目录