单向链表

#include<iostream>
using namespace std;
class Chain;

class Node
{
	friend class Chain;

private:

	char data;
	Node *next;
	
};

class Chain
{

public:
	
	Chain();
	~Chain();
	void ClearList();//将表清空
	bool Find(int i , char &x); //将下标为i的元素取至x中
	int Search(const char &x);//返回x在表中的下标
	bool Insert(int i, const char &x);//在下标为i的结点前插入x
	bool Delete(int i ,char &x);//将下标为i的结点的值存入x,并删除i
	void Output();//输出表中所有元素


private:

	Node *head; //头指针
	int length; //表长
	

};

Chain::Chain()  //构造函数
{

	head = new Node;  //为头指针申请头结点,也即head指向的是头结点
	                  //头结点不是第一个结点,

	head->next = 0;   //头结点不指向任何地方
	length = 0;
}

Chain::~Chain()  //析构函数
{
    ClearList();
	delete head;
}

bool Chain::Find(int i , char &x) //将下标为i的元素取至x中
{
	if(i<0 || i>length -1) return false;
	Node *p = head->next;

	int k = 0;

	while(k<i)  //将p指向第i个元素
	{
		p = p->next;
		k++;
	}
	x = p->data;
	return true;
}

int Chain::Search(const char &x) //找到与元素x相等的元素并返回下标
{
	Node *p = head->next;
	int i = 0;

	while(p != 0)
	{
	    if(p->data == x) return i;
		p = p->next;
		i++;
	}
	return -1;
}

bool Chain::Insert(int i, const char &x) //将x插入第i个元素前面
{
	if(i < 0 || i > length) return false;
	Node *p = head;

	int k = 0;

	while(k <= i-1){p = p->next; k++;}

	Node *q;
	q = new Node;

	q->data = x;
	q->next = p->next;
	p->next = q;
	length++;
	return true;
}

bool Chain::Delete(int i ,char &x)//将下标为i的结点的值存入x,并删除i
{
	if(i < 0 || i > length) return false;
	Node *p = head;
	for(int k =0; k<i; k++) p = p->next;//找到第i个结点的前一个结点p

	Node *q = p->next;//第i个结点为q

	x = q->data;
	p->next = q->next;

	delete q;
	length--;
	return true;
}

void Chain::ClearList()
{

	Node *p = head->next, *q;
	while(p != 0)  //p在前,q在后,删除p后第二次循环又是p在前,q在后
	{
		q = p;
		p = p->next;
		delete q;
	
	}
	head->next = 0;
	length = 0;
}

void Chain::Output()
{
	Node *p = head->next;
	while(p != 0)
	{
	   cout<<p->data;
	   p = p->next;	
	}
}

void main()
{
	char str[] = "ABCDEFG";
	Chain L;
	for(int i = 0; str[i] != '\0';i++)
	{
		L.Insert(i,str[i]);

	}
	L.Output();
	cout<<endl;
	system("pause");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值