美文网首页
Leetcode 82. Remove Duplicates f

Leetcode 82. Remove Duplicates f

作者: persistent100 | 来源:发表于2017-07-25 16:31 被阅读0次

题目

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.

分析

已排序的链表,删除含有重复数字的节点,只保留独特的值。因此可以依次遍历链表,找到重复的,就直接略去。不重复的就需要保留。特别注意的是链表首尾节点的处理,容易出错。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
    struct ListNode *p=head,*q=head;
    bool firstnode=true;
    if(p==NULL)return head;
    while(p!=NULL)
    {
        int num=0;
        while(p->next!=NULL && p->val== p->next->val)
        {
            num++;
            p=p->next;
        }
        if(p->next==NULL)
        {
            if(firstnode==true)
            {
                if(num==0)
                    head=p;
                else
                    head=NULL;
            }
            else
            {
                if(num==0)
                    q->next=p;
                else
                    q->next=NULL;
            }
            break;
        }
        if(num>0)
        {
            p=p->next;
        }
        else
        {
            if(firstnode==true)
            {
                head=p;
                q=p;
                p=p->next;
                firstnode=false;
            }
            else
            {
                q->next=p;
                q=p;
                p=p->next;
            }
        }
    }
    return head;
}

相关文章

网友评论

      本文标题:Leetcode 82. Remove Duplicates f

      本文链接:https://www.haomeiwen.com/subject/rttgkxtx.html