洛谷题:链表知识

题目来自洛谷社区:

 我的第一种做法,用C++库里面的list,还有算法库里的find函数,感觉代码很简单,但是通过不了,运行超时。

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main()
{
	list<int> a;
	a.push_back(1);
	int m;
	int lo,st;
	cin >> m;
	list<int>::iterator it;
	for(int i = 2;i<= m;i++)	
	{
		cin >> lo >> st;
		it = find(a.begin(),a.end(),lo);
		if(st == 0)
			a.insert(it,i);
		else
			a.insert(++it,i);
	}

	int n,x;
	cin >> n;
	for( int i = 1; i<=n;i++)
	{
		cin >> x;
		it = find(a.begin(),a.end(),x);
		if(it == a.end())
		continue;
			a.erase(it);
	}
	for(it = a.begin();it!=a.end();it++)
	{
		cout << *it<<' ';
	}
	cout << endl;
	return 0;
	
}

所以想想还是要找一下第二种方法:

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

struct N
{
	int no;
	N *next;
	N *front;
}node[100000];

int main()
{
	int m;
	cin >> m;
	N *head = NULL;
	N *tail = NULL;
	for(int i = 1; i<=m;i++)
	{
		node[i].no = i;
		node[i].next = NULL;
		node[i].front = NULL;
	}
	int lo,st;
	head = &node[1];
	for(int i = 2; i <= m ;i++)
	{
		cin >> lo >> st;
		if(st == 0)
		{
			if(&node[lo] == head)
			{
					head->front = &node[i];
					node[i].next = head;
					head = &node[i];

			}
			else
			{
				node[lo].front->next = &node[i];
				node[i].front = node[lo].front;
				node[i].next = &node[lo];
				node[lo].front = &node[i];
			}
		}
		else
		{
			if (node[lo].next == NULL)
			{
				node[lo].next = &node[i];
				node[i].front = &node[lo];
				node[i].next = NULL;
			}
			else
			{
				node[i].next = node[lo].next;
				node[i].next->front = &node[i];
				node[lo].next = &node[i];
			}
		}
	
	}
	int n,x;
	cin >> n;
	N *p2;
	for(int i =1;i<=n;i++)
	{
		cin >> x;
		N *p2 = &node[x];
		if (p2)
		{
			if ( node[x].no == head->no) 
				head = node[x].next;
			else
			{
				node[x].front ->next = node[x].next;
				node[x].next->front=  node[x].front;
			}
			free(p2);
		}
	}

	 N *p = head;
	while(p)
	{
	cout << p->no;
	cout<<endl;
	p = p->next;
	}
	return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值