简单数据结构之循环链表(C++实现)

/*
 ============================================================================
 Name        : Circular link.cpp
 Author      : ntsk13 [email protected]
 Version     :
 Copyright   : GPL
 Description : circular Link list study, complement by C++
 Date        : 2015.06.16
 ============================================================================
 */

#include 

using namespace std;

typedef struct {
	int data;
}Elem_t;

typedef struct lnode{
	Elem_t e;
	struct lnode * next;
}node,*pnode;

class Link
{
public:
	void init(pnode & L);
	void clear(pnode & L);
	int  get_length(pnode &L);
	Elem_t get_elem(pnode &L,int i);

	void traverse(pnode &L);
	void insert(pnode &L,Elem_t e,int i);
	void delete_elem(pnode &L,int i);
};


int main(void) {
	pnode H=NULL;//head p
	Elem_t zero,one,two,three,four,five;
	zero.data=0;
	one.data=1;
	two.data=2;
	three.data=3;
	four.data=4;

	Link list;

	list.init(H);
	list.insert(H,zero,0);
	list.insert(H,one,1);
	list.insert(H,two,2);
	list.insert(H,three,3);
	list.insert(H,four,4);

	list.traverse(H);
	cout<<"len is "<e).data =0;//头结点的data作为长度
	L->next=L;

}
void Link::clear(pnode & L)
{
	int i=0;
	pnode p=L;
	pnode tmp=NULL;
	int len=(L->e).data;
	for(i=0;inext;
		delete p;
		p=tmp;
	}
	L=NULL;

}

int Link::get_length(pnode & L)
{
	return (L->e).data;;
}
Elem_t Link::get_elem(pnode & L,int i)
{
	int j=0;
	pnode p=L->next;
	while(j next;
	}
	return p->e;
}

void Link::traverse(pnode & L)
{
	int i=0;
	pnode p=L->next;//避免把头指针元素输出
/* 1) 以长度作为循环链表是否结束的依据
 * 	int len= (L->e).data;
	for(i=0;i< len;i++)
	{
		cout<<"The "<e).data<next;
	}
*/
	//2)以 next 指针指向 头指针 作为结束标识

	while(p != L)
	{
		cout<<"The "<e).data<next;
	}
}

void Link::insert(pnode & L,Elem_t e,int i)// before i insert
{
	int j=0;
	pnode p=L;
	pnode tmp=NULL;
	for(j=0;j< i;j++)
	{
		p=p->next;
	}
	tmp=new node;
	(tmp->e).data=e.data;

	tmp->next=p->next;
	p->next=tmp;
	( L->e).data++;

}
void Link::delete_elem(pnode & L,int i)
{
	int j=0;
	pnode p=L->next;
	pnode tmp=NULL;
	for(j=0;j< i-1;j++)
	{
		p=p->next;
	}
	tmp=p->next;//将要被free的节点
	p->next=p->next->next;//下一节点指向 下下一节点
	(L->e).data--;//长度减一
	delete  tmp;
}

你可能感兴趣的:(步步为营学算法)