uva133 利用指针编写双向循环链表

我看了网上的一下代码,基本都没有利用指针编写双循环列表的,我就试了一下,主要是想锻炼一下利用指针编基本的数据结构。虽然没有AC,是runtime error,因为数据量太小,利用指针反而没有什么优势,而且我的代码确实效率比较低,毕竟第一次编写双循环链表。

通过这个程序还是发现了不少的问题,比如指针释放啊,循环的时候指针的指向啊,删除插入节点的写法啊,以及删除某个节点是还需要讨论其是否是头指针的后一个和尾指针的前一个等等情况,对于熟悉基本数据结构的实现还是很有帮助的。

#include<iostream>
using namespace std;
bool isend=0;
struct node
{
	int id;
	bool fchosen;				//chosen=1 means selected by first official,otherwise chosen=2
	bool schosen;
	node* prior;
	node* next;

};
class collink
{
public:
	node* front;
	node* rear;
	collink(){front=new node;front->prior=NULL;front->next=NULL;}
	collink(int n);
	~collink();
	void nextmove(node* &cur,int k);
	void priormove(node* &cur,int m);
	void clear_print_node(node* &fcur,node* &scur);
};
collink::collink(int n)
{
	front = new node;
	front->prior=NULL;
	rear = new node;
	rear->next=NULL;
	front->fchosen=front->schosen=rear->fchosen=rear->schosen=0;
	
	node* lastnode= new node;
	lastnode->id=n;
	lastnode->fchosen=lastnode->schosen=0;
	front->next=lastnode;
	lastnode->next=rear;
	lastnode->prior=front;
	rear->prior=lastnode;
	for (int i=n-1;i>=1;i--)
	{
		node *p = new node;
		p->id=i;
		p->fchosen=p->schosen=0;
		p->next=front->next;
		front->next->prior=p;
		p->prior=front;
		front->next=p;
	}
	rear->prior->next=front->next;
	front->next->prior=rear->prior;
}
collink::~collink()
{
	delete front;
	delete rear;

}
void collink::nextmove(node* &cur,int k)
{
	while(k--)
	{
		cur=cur->next;
	}
	cur->fchosen=1;
}
void collink::priormove(node* &cur,int m)
{
	while(m--)
	{
		cur=cur->prior;
	}
	cur->schosen=1;
}
void collink::clear_print_node(node* &fcur,node* &scur)
{
	node* cur=front;
	int len=0;
	while(cur!=rear->prior)
	{
		len++;
		cur=cur->next;
	}
	if (len==1)
	{
		cout<<"  "<<cur->id<<endl;
		isend=1;
	}
	else
	{
		int count=0;
		int output[2];
		bool flag=0;
		while(count!=2)
		{
			cur=cur->next;
			if (cur->fchosen==1&&cur->schosen==0)
			{
				output[0]=cur->id;
				count++;
				fcur=fcur->prior;
				
			}
			else if (cur->fchosen==0&&cur->schosen==1)
			{
				output[1]=cur->id;
				count++;
				scur=scur->next;
			}
			else if (cur->fchosen==1&&cur->schosen==1)
			{
				cout<<" "<<cur->id<<",";
				count=2;
				flag=1;
				fcur=fcur->prior;
				scur=scur->next;
				
			}
			else continue;
			node* p =cur;
			p->prior->next=p->next;
			p->next->prior=p->prior;
			cur=cur->prior;			
			if (p==front->next)
			{
				front->next=p->next;
			}
			if (p==rear->prior)
			{
				rear->prior=p->prior;
			}
			delete p;
		}
		if (flag==0)
		cout<<"  "<<output[0]<<"  "<<output[1]<<",";
	}
	
};
int main()
{
	int n,k,m;
	while(cin>>n>>k>>m&&n!=0)
	{
		collink link(n);
		node* fcur=link.front;
		node* scur=link.rear;
		while(!isend)
		{
			link.nextmove(fcur,k);
			link.priormove(scur,m);
			link.clear_print_node(fcur,scur);
		}
		delete fcur,scur;
	}
	
	return 0;
}


你可能感兴趣的:(C++,链表,指针,uva,双循环)