0082. Remove Duplicates From Sorted List I I

# 82. Remove Duplicates from Sorted List II#

## 题目 #

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

``````
Input: 1->2->3->3->4->4->5
Output: 1->2->5

``````

Example 2:

``````
Input: 1->1->1->2->3
Output: 2->3

``````

## 代码 #

``````
package leetcode

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

// 解法一
return nil
}
}
for front.Next != nil {
if front.Val == cur.Val {
// fmt.Printf("相同节点front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
front = front.Next
continue
} else {
if cur.Next != front {
// fmt.Printf("删除重复节点front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
last.Next = front
if front.Next != nil && front.Next.Val != front.Val {
last = front
}
cur = front
front = front.Next
} else {
// fmt.Printf("常规循环前front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
last = cur
cur = cur.Next
front = front.Next
// fmt.Printf("常规循环后front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)

}
}
}
if front.Val == cur.Val {
// fmt.Printf("相同节点front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
last.Next = nil
} else {
if cur.Next != front {
last.Next = front
}
}
}

// 解法二
return nil
}
}
}
}

return nil
}
}
for cur.Next != nil {
if cur.Next.Val == cur.Val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
}

// 解法三 双循环简单解法 O(n*m)
}

nilNode := &ListNode{Val: 0, Next: head}

lastVal := 0
}
} else {
}
}
return nilNode.Next
}

// 解法四 双指针+删除标志位，单循环解法 O(n)
}

nilNode := &ListNode{Val: 0, Next: head}
// 上次遍历有删除操作的标志位
lastIsDel := false
// 虚拟空结点
// 前后指针用于判断
// 每次只删除前面的一个重复的元素，留一个用于下次遍历判重
// pre, back 指针的更新位置和值比较重要和巧妙
if pre.Val != back.Val && lastIsDel {
lastIsDel = false
continue
}

if pre.Val == back.Val {
lastIsDel = true
} else {
lastIsDel = false
}
}
// 处理 [1,1] 这种删除还剩一个的情况
if lastIsDel && head.Next != nil {