leetcode83 删除排序链表中的重复元素

leetcode83 Remove Duplicates From Sorted List

Posted by BY on November 14, 2018

前言

休息一下

正文

问题来源

本问题来自leetcode上的183题。

问题描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1
输入: 1->1->2
输出: 1->2
示例 2
输入: 1->1->2->3->3
输出: 1->2->3

分析:

注意是排序好了的序列。

func deleteDuplicates(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	cur, next := head, head.Next	
	for next != nil {
		if next.Val == cur.Val {
			cur.Next = next.Next // 删除next			
		} else { // 不等
			cur = next
		}
		next = next.Next
	}	
	return head // head不会变
}

总结:

水一水

结语

不要懒,多看多写。