Skip to content

Latest commit

 

History

History
51 lines (40 loc) · 811 Bytes

083.md

File metadata and controls

51 lines (40 loc) · 811 Bytes

Remove Duplicates from Sorted List

题目

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

思路

part1:
    一次遍历,如果Next的值和当前的值相同则跳过next的值。 

代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
    if head == nil {
        return head
    }
    curNode := head
    for curNode.Next != nil {
        if curNode.Next.Val == curNode.Val {
            curNode.Next = curNode.Next.Next
        } else {
            curNode = curNode.Next
        }
    }
    return head
}