⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 1.cpp

📁 链表的创建
💻 CPP
字号:
#include<iostream>
using namespace std;
struct node
{
	char data;
	node *next;
};
node *create();
void showList(node *head);
node *search(node *head,char keyWord);
void insert(node *&head,char keyWord,char newdata);
void Delete(node *&head,char keyWord);
void destroy(node *&head);

int main()
{
	node *head;
	head=create();//创建链表,并讲表头指针赋给head
	showList(head);//显示链表

	char keyWord,newdata;

	cout<<"输入插入之前得字:"<<endl;
	cin>>keyWord;
	cout<<"输入想插入得字:"<<endl;
	cin>>newdata;
	insert(head,keyWord,newdata);
	showList(head);

	cout<<"输入想要删除得字:"<<endl;
	cin>>keyWord;
	Delete(head,keyWord);
	showList(head);

	destroy(head);

	return 0;
}

node *create()//创建链表
{
	node *head=NULL;
	node *pEnd=head;
	node *pS;
	char temp;
	cout<<"please input the data end with #"<<endl;
	do
	{
		cin>>temp;
		if(temp!='#')
		{
			pS=new node;
			pS->data=temp;
			pS->next=NULL;
			if(head==NULL)
			{
				head=pS;
			}
			else
			{
				pEnd->next=pS;
			}
			pEnd=pS;
		}
	}while(temp!='#');
	return head;
}

void showList(node *head)//显示链表
{
	node *pRead=head;
	cout<<"The data of the link are:"<<endl;
	while(pRead!=NULL)
	{
		cout<<pRead->data;
		pRead=pRead->next;
	}
	cout<<endl;
}


node *search(node *head,char keyWord)//查询数据为keyWord的节点
{
	node *pRead=head;
	while(pRead!=NULL)
	{
		if(pRead->data==keyWord)
		{
			return pRead;
		}
		pRead=pRead->next;
	}
	return NULL;//所有节点都不匹配,返回NULL
}

void insert(node *&head,char keyWord,char newdata)//在链表中,keyWord后面插入newdata
{
	node *newnode=new node;
	newnode->data=newdata;
	node *pGuard=search(head,keyWord);
	if(head==NULL||pGuard==NULL)//如果链表为空或者找不到关键字,则插入表头
	{
		newnode->next=head;
		head=newnode;
	}
	else
	{
		newnode->next=pGuard->next;
	    pGuard->next=newnode;
	}
}


void Delete(node *&head,char keyWord)//删除节点为keyWord得节点
{

	if(head!=NULL)
	{
	    node *pGuard=head;
	    node *p;
		if(head->data==keyWord)
		{
			p=head;
			head=head->next;
			delete p;
			cout<<"the deleted word is "<<keyWord<<endl;
			return;
		}
		else
		{
			while(pGuard->next!=NULL)
			{
				if(pGuard->next->data==keyWord)
				{
					p=pGuard->next;
					pGuard->next=p->next;
					delete p;
					cout<<"the deleted word is "<<keyWord<<endl;
					return;
				}
				pGuard=pGuard->next;
			}
		}
	}
	cout<<"the link or keyWord is empty."<<endl;
}

void destroy(node *&head)
{
	node *p;
	while(head!=NULL)
	{
		p=head;
		head=head->next;
		delete p;
	}
	cout<<"the link is destroyed."<<endl;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -