[leetcode-82]Remove Duplicates from Sorted List II(C)

来源:互联网 发布:单片机无线抢答器 编辑:程序博客网 时间:2024/05/19 22:48

问题描述:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

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

分析:本来以为是很简单的一个问题,结果发现轻敌了,这里面我之前没有思考好每个循环之间的关系。。
从链表头部开始出发,开始判断头部相同值的个数。当为1时,是我们所需要的节点。当》1时,继续循环。也就是当循环退出时,那一定是一个有效的节点。这里面,需要再对head重新赋值。即使它没变,也重新赋值,不然的话就太乱了。
按照我的思路,就是找到所有满足条件的节点并串联起来。

代码如下:4ms

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */ int count(struct ListNode **head){     int count = 1;     while(*head && (*head)->next && (*head)->next->val == (*head)->val){        count++;        *head = (*head)->next;     }    return count; }struct ListNode* deleteDuplicates(struct ListNode* head) {    if(!head)        return head;    struct ListNode *prev = NULL;    struct ListNode *current = head;    struct ListNode *res = head;    while(current){        while(current!=NULL && count(&current)>1){            if(current)                current = current->next;        }        if(!prev){            head = current;        }else            prev->next = current;        prev = current;        if(current)            current = current->next;    }    return head;}
0 0
原创粉丝点击