首页 > 其他 > 详细

Remove Duplicates from Sorted List II--LeetCode

时间:2015-03-31 18:10:13      阅读:289      评论:0      收藏:0      [点我收藏+]

题目:

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.

思路:先锁定头,然后处理中间位置,记得最后处理尾部,知识繁琐,处理头部时,找到一个节点,当前节点没有相同的连续节点,同时节点和后序节点不同。处理中间只需要记录前序节点和遍历节点即可,使得遍历节点没有连续相同的节点。如果有连续相同的节点,那么删除所有的连续相同的节点

#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* pre=head;
	 List* cur;
	 List* fast;
	 if(head->value == head->next->value)
	{
	 while(1)
	 {
	 	while(pre != NULL &&pre->next != NULL)
		 {
	 		if(pre->value == pre->next->value)
	 			pre = pre->next;
	 		else
	 			break;
	 	}	
	 	pre = pre->next;
	 	if(pre->next == NULL || pre->value != pre->next->value)
	 	{
	 		head = pre;
	 		break;
	 	}	 		
	 }	
	} 
	 if(head == NULL)
	 	return ;
	 pre = head;
	 cur=head->next;
	 while(cur !=NULL && cur->next != NULL)
	 {
	 	if(cur->value != cur->next->value)
	 	{
	 		if(pre->next != cur) // 不相邻 
			{
				cur = cur->next; 
				pre->next = cur;
			} 
			else
			{
				pre = cur;
				cur = cur->next;
			}	 		
	 	}
	 	else
	 	{
	 		cur = cur->next;
	 	}
	 }
	if(pre->next!=NULL && pre->next->next !=NULL)
	{
		if(pre->next->value == pre->next->next->value)
			pre->next = NULL;
	}
} 
  
int main() 
{
	int array[]={1,1,1,2,2,3,4,4,4,5,5,7,7,8};
	List* head;
	Init_List(head,array,sizeof(array)/sizeof(int));
	RemoveDuplicate(head);	
	print_list(head); 
	return 0;
}


Remove Duplicates from Sorted List II--LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/44781333

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!