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

📄 单链表的创建.cpp

📁 共有10个文件代码
💻 CPP
字号:
#include<iostream.h>
#include"stdlib.h"//malloc函数需要包含的头文件
struct nodetype
{
	int data;
	nodetype *next;
}typedef Linklist;
Linklist *L;//touzhizhen
nodetype *FindIndex(const int i)
{
	if(i==-1) return L;
	nodetype *p=L;
	int j=0;
	while(p!=NULL&&j<i-1)
	{
		p=p->next;
		j++;
	}
	return p;
}
nodetype *Insert(int value,int i)
{
	nodetype *p,*q;
	q=new nodetype;
	p=FindIndex(i-1);
		if(p==NULL)return NULL;
		q->next=p->next;
		q->data=value;
		p->next=q;
		return q;
}
nodetype *RemoveAfter(int i)
{
	nodetype *p,*q;
	int e;
	p=FindIndex(i-1);
	if(p==NULL)return NULL;
	q=p->next;
	p->next=q->next;
	e=q->data;
	delete(q);
}
void main()
{
    int d;
	nodetype *h=NULL,*s,*t,*p;
	int n,m,x,y;
	cout<<"建立一个单链表:"<<endl;
	cout<<"输入单链表元素个数:";
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cout<<"输入第"<<i<<"结点值";
		cin>>d;
		if(i==1)
		{
			h=(nodetype*)malloc(sizeof(nodetype));
			h->data=d;
			h->next=NULL;
			L=h;//输出的需要
			t=h;
		}
		else{
			s=(nodetype*)malloc(sizeof(nodetype));
			s->data=d;
			s->next=NULL;
			t->next=s;
			t=s;//t始终指向最后一个结点
		}
	}
	p=L;
	cout<<"创建的链表为:"<<endl;
	while(p!=NULL)					
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
	cout<<"输入要插入的位置:";cin>>m;
		cout<<"输入要插入的元素:";	cin>>x;
    Insert(x,m);
	cout<<"插入新元素后链表为:"<<endl;
	p=L;
	while(p!=NULL)					
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
	cout<<"输入要删除的元素位置:";cin>>y;
	RemoveAfter(y);
	cout<<"删除后链表为:";
	p=L;
	while(p!=NULL)					
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
}

⌨️ 快捷键说明

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