[C语言][LeetCode][83]Remove Duplicates from Sorted List

题目

Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

标签

Linked List

难度

简单

分析

题目意思是给定一个单链表,去除重复的节点,返回新链表。解题思路是,用一个临时指针指向list,如果p->val == p->next->val,则将p指针跳过p->next,指向p->next->next。

C代码实现

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
struct ListNode* deleteDuplicates(struct ListNode* head) {
    struct ListNode * p;
    p = head;

    if(!head)
        return NULL;

    while(p && p->next)
    {
        if(p->val == p->next->val)
            p->next = p->next->next;
        else
            p = p->next;
    }

    return head;    
}

你可能感兴趣的:(LeetCode,算法,C语言)