单链表

本文介绍了一个简单的链表类实现,包括创建链表、插入、删除、查找和逆置等基本操作,并通过一个示例程序展示了这些功能的具体使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct Node
{
	ElemType data;
	Node *next;
}ListNode;
class List
{
public:
	List();
	ListNode* CreateList(ListNode *&root,int n);
	ListNode* Locate(ListNode *root,int i,ElemType &e);
	bool     Insert(ListNode *&root,int i,ElemType e);       //第i个元素前插入元素
	bool     Delete(ListNode *&root,int i,ElemType &e);
	void     Display(ListNode *root);
	void     Review(ListNode *&root);          //带头结点的链表逆置
private:
	ListNode *root;
};

List::List()
{
	root=new ListNode;
	root->next=NULL;
}

ListNode* List::CreateList(ListNode *&root,int n)
{
	//创建n个结点,
	ListNode *last=new ListNode;
	int i,key;
	last=root;
	last->next=NULL;
	cout<<"请依次输入节点数据"<<endl;
	for(i=0;i<n;++i)
	{
		ListNode *newNode=new ListNode;
		cin>>key;
		newNode->data=key;
		newNode->next=NULL;
		newNode->next=last->next;
		last->next=newNode;
		last=newNode;
	}
	return root;
}

void List::Display(ListNode *root)
{
	while (root->next)
	{
		cout<<root->next->data<<" ";
		root=root->next;
	}
}

ListNode* List::Locate(ListNode *root,int n,ElemType &e)
{
	if(n<=0) return root;
	for(int i=0;i<n;++i)
	{
		root=root->next;
		if(!root)
		return NULL;
	}
	e=root->data;
	return root;
}
bool List::Insert(ListNode *&root,int i,ElemType e)
{
	if(i<0) return false;
	int d;
	ListNode *current=Locate(root,i-1,d);
	if(!current)  return false;
	ListNode *newNode=new ListNode;
	newNode->data=e;
	newNode->next=NULL;
	newNode->next=current->next;
	current->next=newNode;
	return true;
}

bool List::Delete(ListNode *&root,int i,ElemType &e)
{
	if(i<1) return false;
	ElemType temp;
	ListNode *current=Locate(root,i-1,temp);
	ListNode *del=current->next;
	current->next=del->next;
	e=del->data;
	cout<<e<<"所为删除节点"<<endl;
	delete del;
	return true;
}

void List::Review(ListNode *&root)
{
	ListNode *pre=new ListNode;
	ListNode *p=new ListNode;
	p=NULL;
	pre=root->next;
	ListNode *current=pre->next;
	for(current;current!=NULL;current=current->next)
	{
		pre->next=p;
		p=pre;
		pre=current;
	}
	pre->next=p;
	root->next=pre;
}
int main()
{
	List a;
	ListNode *root=new ListNode;
	cout<<"要输入几个数据"<<endl;
	int n,temp;
	ElemType e,y;
	cin>>n;
	root=a.CreateList(root,n);
	cout<<"创建成功,链表所含节点"<<endl;
	a.Display(root);
	cout<<endl;
	cout<<"删除函数测试,请输入删除节点的信息(第几个)"<<endl;
	cin>>temp;
	if(!a.Delete(root,temp,e))
	cout<<"删除错误!"<<endl;
	cout<<"删除后的链表: ";
	a.Display(root);
	cout<<endl;
	cout<<"增加函数测试,请输入要插入的位置和节点的值"<<endl;
	cin>>temp>>y;
	if(!a.Insert(root,temp,y))
	cout<<"插入错误!"<<endl;
	cout<<"插入后的链表"<<endl;
	a.Display(root);
	cout<<endl;
	cout<<"链表逆置测试"<<endl;
	a.Review(root);
	a.Display(root);
	system("pause");
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值