Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
题目分析:删除链表中的重复元素,实现逻辑
- 判断当前元素是否和下一个元素相同,相同则将下一个元素在链表中删除,不相同则将指针指向下一个元素
func deleteDuplicates(head *ListNode) *ListNode {
tmp := head
for head != nil {
if head .Next!=nil && head.Val ==head.Next.Val {
nextP := head.Next.Next
for nextP != nil {
if nextP.Val != head.Val {
break
}
nextP = nextP.Next
}
head.Next = nextP
}
head = head.Next
}
return tmp
}