循环链表

循环链表的操作和线性链表基本一致,差别仅仅在算法中的循环条件,p或p->next 是否为空

数据结构 循环链表_单向链表

下面是代码:

 

#include<iostream>
#include<stdlib.h>
#include<algorithm>
#define initSize 100  
using namespace std;

typedef int dataType;
class node {
	friend class nodeList;
private:
	dataType data;   
	node* link;     
};


class nodeList {
private:
	node* first;    
public:
	nodeList() {
		first = new node();
		first->link = first;     //这里的设置和单向链表不同 头表节点指向了自己
	}

	void add(dataType num);           
	void insertTail(dataType num);   
	void mediumInsert(dataType num, int pos);
	void Delete(dataType num);   
	void show();
};

//显示函数
void nodeList::show() {
	node* p = new node();
	p = first->link;      //这里的设置和单向链表不同 遍历的第一个节点是头表节点的下一个
	 

	while (p != first) {    //循环的终止条件变了 只要不指向下一个 则继续遍历
		dataType temp = p->data;
		cout << temp << "  ";
		p = p->link;
	}
	cout << endl;
}

//插入函数 从头插入
void nodeList::add(dataType num) {
	node* newNode = new node();
	newNode->data = num;

	newNode->link = first->link;
	first->link = newNode;       //这里是个坑 first本身是个空节点 专门用来做表头
}

//插入尾部
void nodeList::insertTail(dataType num) {
	node* newNode = new node();
	newNode->data = num;

	node* p = new node();   
	p = first->link;    //first的下一个为第一个非空节点

	while (p->link != first) {   //不是头节点的话
		p = p->link;
	}

	newNode->link = p->link;
	p->link = newNode;

}

//中间部分插入
void nodeList::mediumInsert(dataType num, int pos) {
	node* newNode = new node();
	newNode->data = num;

	node* p = new node();   
	p = first->link;
	
	int k = 0;   

	while (p->link != first && k < pos - 1) {
		p = p->link;
		k++;
	}

	newNode->link = p->link;
	p->link = newNode;
}


void nodeList::Delete(dataType num) {
	node* p = new node();
	node* q = new node();

	p = first->link;
	q = NULL;

	if (p->data == num) {
		first->link = p->link;   //坑
		delete p;
		return;
	}
	else {
		while (p != first) {
			q = p->link;
			if (q->data == num) {
				p->link = q->link;   
				delete q;
				break;
			}
			p = p->link;
		}
	}
}



void main() {

	nodeList MyList;
	MyList.add(30);
	MyList.add(15);
	MyList.add(20);

	MyList.show();
	MyList.insertTail(999);
	MyList.show();
	MyList.mediumInsert(30,5);  
	MyList.show();
	MyList.Delete(15);
	MyList.show();
	
	
	system("PAUSE");
	return;
}