LeetCode 83 Remove Duplicates from Sorted List

来源:互联网 发布:时序数据分类基本原理 编辑:程序博客网 时间:2024/05/18 03:51

 题目:

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

AC不过,但是经过自己代码测试发现可以,不知为何.

ListNode* deleteDuplicates(ListNode* head) {        if(head==NULL)        return NULL;               ListNode *cur=head;        while(cur->next!=NULL)        {         if(cur->next->val!=cur->val)    {        cur=cur->next;        }        else         {            ListNode *del=cur->next;         if(del->next==NULL)         {         delete del;         }         else         {         cur->next=del->next;         delete del;        }        }        }          return head;       }
网上搜索到不需要删除的重组方案,耳目一新

class Solution {  public:      ListNode *deleteDuplicates(ListNode *head) {          if(head==NULL)              return head;          ListNode* p=head;          ListNode* q=head->next;          while(q!=NULL){              if(q->val==p->val) {                  p->next = q->next;              }else{                  p=q;              }              q = q->next;          }          return head;      }  }; 



0 0
原创粉丝点击