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

来源:互联网 发布:开户数据 编辑:程序博客网 时间:2024/06/05 19:06

一天一道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;    }};
1 0
原创粉丝点击