leetcode 之Remove Duplicates from Sorted List(17)

很简单的一题,需要注意的是如果某结点重复了记得将其删除。

ListNode *deleteDuplicates(ListNode *head)
      {

          if (head == nullptr)
              return nullptr;
          ListNode *prev = head;
          for (ListNode *cur = head->next; cur != nullptr; cur = cur->next)
          {
              if (cur->val == prev->val)
              {
                  prev->next = cur->next;
                  
                  delete cur;
              }
              else
                  prev->next = cur;
          }
      }
View Code

 

这题采用递归来做,当两结点不等时,注意递归调用的形式。

ListNode *deleteDuplicates2(ListNode *head)
   {
       if (!head || !head->next)return head;
       ListNode *p = head->next;
       if (p == head)
       {
           while (p&&p==head)
           {
             ListNode *temp = p;
             p = p->next;
             delete temp;

           }
           delete head;
           return deleteDuplicates2(p);
       }
       else
       {
           head->next=deleteDuplicates2(head->next);
           return head;
       }
   }
View Code

 

posted @ 2016-05-18 15:34  牧马人夏峥  阅读(124)  评论(0编辑  收藏  举报