这是第一次认认真真的写链表,有很多不足,留个纪念~~
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<map>
#include<cmath>
#include<string>
#include<deque>
#include <vector>
using namespace std;
typedef long long ll;
#define PI acos(-1)
#define MAX 0x3f3f3f3f
typedef struct Lnode
{
int data;
Lnode *next;
}Lnode;
int n;//记录表长
void Creat(Lnode *L)//创建链表
{
Lnode *p,*q;
L->next=NULL;
int a;
q=L;
while(1)
{
cout<<"请输入数据(输入以0结束):";
cin>>a;
if(a==0)
break;
p=(Lnode*)malloc(sizeof(Lnode));
p->data=a;
n++;
p->next=NULL;
q->next=p;
q=p;
}
}
void Printf(Lnode *L)//输出链表
{
cout<<"输出所有的结点"<<endl;
Lnode *p;
p=L->next;//从L的下一位置开始存数
while(p)
{
cout<<p->data<<endl;
p=p->next;
}
}
void Insert(Lnode *L)//插入结点
{
Lnode *p,*q;
int a,b;
cout<<"请输入在1-"<<n<<"大小的数:(即在该位置后面插入)";
cin>>a;
cout<<"请输入你要插入节点的值:";
cin>>b;
p=L;
q=(Lnode*)malloc(sizeof(Lnode));
while(a--)
{
p=p->next;
}
q->data=b;
q->next=p->next;
p->next=q;
n++;
}
void Delete(Lnode *L)//删除结点
{
Lnode *p,*q;
cout<<"输入你要删除的结点的序号:"<<endl;
int a;
cin>>a;
p=L;
a--;
while(a--)
p=p->next;
q=p->next;
p->next=p->next->next;
n--;
free(q);
}
int main()
{
Lnode L;
cout<<"创建链表:"<<endl;
Creat(&L);
Printf(&L);
Insert(&L);
Printf(&L);
Delete(&L);
Printf(&L);
return 0;
}