题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留。
样例
输入:1->2->3->3->4->4->5
输出:1->2->5
golang 代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
//安全删除节点
func deleteDuplication(head *ListNode) *ListNode {
if head == nil {
return nil
}
//返回节点
var ans = new(ListNode)
ans = nil
var flag = true
var temp,prenode = head,head
//扫描一遍,找出待删除节点值
var exist = make(map[int]bool)
for temp != nil {
_, ok := exist[temp.Val];
if !ok {
exist[temp.Val] = false
}else{
exist[temp.Val] = true
}
temp = temp.Next
}
//节点删除
for head != nil {
if exist[head.Val] {
delete := head
head = head.Next
prenode.Next = head
delete.Next = nil
}else{
if flag {
ans = head
flag = false
}
prenode = head
head = head.Next
}
}
return ans
}