Remove Duplicates from Sorted List II

来源:互联网 发布:人工智能会毁灭人类 编辑:程序博客网 时间:2024/05/20 13:06

一、问题描述

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) return NULL;        if(!head -> next)  return head;                ListNode* p = head -> next;        int data = head -> val;        if(p -> val != data){            head -> next = deleteDuplicates(p);            return head;        }else{            while(p && p -> val == data) p = p -> next;            return deleteDuplicates(p);        }            }};


0 0
原创粉丝点击