Remove Duplicates from Sorted List II

来源:互联网 发布:linux改root密码 编辑:程序博客网 时间:2024/05/04 12:50

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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.

1、题目解析:

(1)主要解决开始几个是重复数字的情况,这里可以使用递归的方法。


#include <iostream>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};ListNode *deleteDuplicates(ListNode *head) {if(head == NULL || head->next == NULL)return head;ListNode *p = head->next;int count = 1;while(p!=NULL && p->val == head->val){count++;p = p->next;}if(p == NULL){head = NULL;return head;}if(count >= 2)return deleteDuplicates(p);else{ListNode *q = head;while(q!=NULL && q->next!=NULL){ListNode *r = q->next;int sunCount = 0;while(r!=NULL && r->val == q->next->val){r = r->next;sunCount++;}if(sunCount >= 2){q->next = r;}else{q = q->next;}}}return head;}int main(void){ListNode *head;ListNode *node = (ListNode *)malloc(sizeof(ListNode));node->val = 1;head = node;ListNode *p = head;node = (ListNode *)malloc(sizeof(ListNode));node->val = 1;p->next = node;p = node;node = (ListNode *)malloc(sizeof(ListNode));node->val = 2;p->next = node;p = node;p->next = NULL;deleteDuplicates(head);system("pause");return 0;}


0 0
原创粉丝点击