Delete duplicate elements in sorted linked list---Likou

1 question

There is a linked list arranged in ascending order. Given the head node of this linked list, please delete all duplicate elements so that each element appears only once.

Returns a linked list of results also sorted in ascending order.
Insert image description here

输入:head = [1,1,2]
输出:[1,2]

Insert image description here

输入:head = [1,1,2,3,3]
输出:[1,2,3]

2 answers

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

If cur.Next.Next=nil in the last round, nil will be returned directly.

3Related links

https://blog.csdn.net/Roxin_238/article/details/104724850

Guess you like

Origin blog.csdn.net/weixin_42375493/article/details/122046442