码迷,mamicode.com
首页 > 其他好文 > 详细

【一天一道LeetCode】#82. Remove Duplicates from Sorted List II

时间:2016-06-06 01:10:53      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
         if(head==NULL) return head;//链表为空
         ListNode* newHead = NULL;//新链表头
         ListNode* newtail = NULL;//新链表位
         ListNode* p = head;
         bool ishead = true;//确定新链表的头
         while(p!=NULL)
         {
             ListNode* pnext = p->next;
             int count = 1;
             while(pnext!=NULL&&pnext->val==p->val) {//后续节点与p是否重复
                 count++;
                 pnext = pnext->next;
             }
             if(count==1){//等于1代表没有重复
                 if(ishead) {newHead = p;newtail = newHead;newtail->next=NULL;ishead =false;}//头结点需要特殊处理
                 else {
                     newtail->next = p;
                     newtail = newtail->next;
                     newtail->next=NULL;//这里注意一定要将尾节点的next指向NULL,不然就指向原链表的p的下一个了
                 }
             }
             p = pnext;
         }
         return newHead;
    }
};

【一天一道LeetCode】#82. Remove Duplicates from Sorted List II

标签:

原文地址:http://blog.csdn.net/terence1212/article/details/51589504

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!