删除链表中的重复接点

题目要求参考剑指offer面试题目57
#include<iostream>
using namespace std;
struct Node{
	int data;
	Node *next;
	Node(int value):data(value),next(NULL){}
};
Node *create_link()
{
	Node *node1=new Node(1);
	Node *head=node1;
	Node *p,*q;
	for(int i=1;i<=2;++i)
	{
		p=new Node(2);
		if(head->next==NULL)
		{
			head->next=p;
		}
		else
		{
			q->next=p;
		}
		q=p;
	}
	for(int i=1;i<=2;++i)
	{
		p=new Node(3);
		if(head->next==NULL)
		{
			head->next=p;
		}
		else
		{
			q->next=p;
			//q=p;
		}
		q=p;
	}
	Node *node=new Node(4);
	q->next=node;
	//q->next=head->next->next;
	return head;

}
void print(Node *head)
{

	/*for(int i=0;i<6;++i)
	{
		cout<<head->data<<endl;
		head=head->next;
	}*/
	Node *p=head;
	while(p)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
}

Node *delete_duplication(Node **head)
{
	if(head==NULL||*head==NULL)
	{
		return NULL;
	}
	Node *pre_node=NULL;
	Node *cur_node=*head;
	while(cur_node!=NULL)
	{
		bool flag=false;
		Node *next=cur_node->next;
		if(next!=NULL&&next->data==cur_node->data)
		{
			flag=true;
		}
		if(!flag)
		{
			pre_node=cur_node;
			cur_node=cur_node->next;
		}
		else
		{
			int value=cur_node->data;//the most important part,we can delete the last node by this value
			Node *deleted=cur_node;
			while(deleted!=NULL&&deleted->data==value)
			{
				next=deleted->next;
				delete  deleted;
				deleted=NULL;
				deleted=next;
			}
			if(pre_node==NULL)
			{
				*head=next;
			}
			else
				pre_node->next=next;
			cur_node=next;
		}

	}
	return *head;
}
int main()
{
	Node *head=create_link();
	delete_duplication(&head);
	print(head);
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值