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

leetcode_82_Remove Duplicates from Sorted List II

时间:2015-02-13 11:44:15      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   linked_list   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Remove Duplicates from Sorted List II

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.




这个题目在函数里单独弄了ListNode作为新的head,这样的话在循环里面可以统一处理而不用把开头的特殊情况拿出来


//方法一:测试Accepted
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
		bool signal = false;
		ListNode tempHead(0);
		if(!head) {
			return head;
		}
		ListNode *first = head, *second = head -> next, *pre = &tempHead;
		tempHead.next = head;
		while(second) 
		{
			while(second && first -> val == second -> val) 
			{
				signal = true;
				first = second;
				second = second -> next;
			}
			if(!signal) 
			{
				pre = first;
				first = second;
				second = second -> next;
			}
			else 
			{
				pre -> next = second;
				first = second;
				if(second) 
					second = second -> next;
			}
			signal = false;
		}
		return tempHead.next;
    }
};



#include<iostream>

using namespace std;

#define N 7

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
		bool signal = false;
		ListNode tempHead(0);
		if(!head) {
			return head;
		}
		ListNode *first = head, *second = head -> next, *pre = &tempHead;
		tempHead.next = head;
		while(second) 
		{
			while(second && first -> val == second -> val) 
			{
				signal = true;
				first = second;
				second = second -> next;
			}
			if(!signal) 
			{
				pre = first;
				first = second;
				second = second -> next;
			}
			else 
			{
				pre -> next = second;
				first = second;
				if(second) 
					second = second -> next;
			}
			signal = false;
		}
		return tempHead.next;
    }
};

ListNode *creatlist(){
	ListNode *list;
	list = NULL;
	ListNode *p;
	for(int i=0; i<N; i++)
	{
		int a;
		cin>>a;
		p = (ListNode*)malloc(sizeof(ListNode));
		p->val = a;
		p->next=list; //指定后继指针
		list = p; //head指针指定到新插入的结点上
	}
	return list;
}

int main()
{
	ListNode *list = creatlist();

	Solution lin;
	ListNode *outlist=lin.deleteDuplicates(list);
	for(int i=0; i<N; i++)
	{
		cout<<outlist->val;
		outlist = outlist->next;
	}
}


leetcode_82_Remove Duplicates from Sorted List II

标签:c++   leetcode   linked_list   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43791975

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