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

Remove Duplicates from Sorted List--LeetCode

时间:2015-03-31 10:53:11      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

思路:和数组删除很相似

#include <iostream>
#include <vector>
using namespace std;

typedef struct list_node List;
struct list_node
{
	int value;
	struct list_node* next;
};

void Init_List(List*& head,int* array,int n)  
{  
    head = NULL;  
    List* tmp;  
    List* record;  
    for(int i=1;i<=n;i++)  
    {  
        tmp = new List;  
        tmp->next = NULL;  
        tmp->value = array[i-1];  
        if(head == NULL)  
        {  
            head = tmp;  
            record = head;  
        }  
        else  
        {  
            record->next = tmp;  
            record = tmp;  
        }  
    }  
}  
void print_list(List* list)  
{  
    List* tmp=list;  
    while(tmp != NULL)  
    {  
        cout<<tmp->value<<endl;  
        tmp = tmp->next;   
    }  
}  
  
void RemoveDuplicate(List*& head)
{
	if(head == NULL || head->next==NULL)
		return ;
	List* low= head;
	List* fast = head->next;
	List* tmp;
	while(fast != NULL)
	{
		if(low->value == fast->value)
		{
			tmp = fast;
			fast = fast->next;
			low->next = fast;
			delete tmp;
		}
		else
		{
			low = low->next;
			fast = fast->next;
		}
			
	}
} 
  
int main() 
{
	int array[]={1,1,1,2,3,3,4,5,6,6,7,7};
	List* head;
	Init_List(head,array,sizeof(array)/sizeof(int));
	RemoveDuplicate(head);	
	print_list(head); 
	return 0;
}


Remove Duplicates from Sorted List--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44775127

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