【数据结构】非指针方法实现单链表(c++)

#include
using namespace std;
const int N = 100010;
//head表示头结点的下标
//e[i]表示i节点的值 
//ne[i]表示i的next指针
//idx存储当前用到哪个点 
int head,e[N],ne[N],idx;

//初始化
void init()
{
	head = -1;
	idx = 0;
 } 
 
//将x插入到头节点
void add_to_head(int x)
{
	e[idx] = x;
	ne[idx] = head;
	head = idx;
	idx ++ ;
 } 
 
//将x插入到下标是k的点的后面
void add_behind_k(int k,int x)
{
	e[idx] = x;
	ne[idx] = ne[k];
	ne[k] = idx;
	idx ++ ;
 } 

//将下标是k的点的后面的点删除
void delete_behind_k(int k)
{
	ne[k] = ne[ne[k]];
 } 
 
int main()
{
	int m;
	cin >> m;
	init();
	while( m-- )
	{
		int k,x;
		char c;
		cin >> c;
		if(c == 'H')
		{
			cin >> x;
			add_to_head(x);
		}
		else if(c == 'D')
		{
			cin >> k;
			if(!k)
			{
				head = ne[head];
			}
			delete_behind_k(k - 1);
		}
		else
		{
			cin >> k >> x;
			add_behind_k(k - 1,x);
		}
	}
	for(int i = head;i != -1;i = ne[i])
	{
		cout << e[i] << ' ' ;
	}
}

注:该方法用数组模拟单链表的结构,适合有时间限制的算法题

你可能感兴趣的:(c++,数据结构,算法)