您的位置:首页 > 编程语言 > C语言/C++

用c++写的链表

2016-05-31 18:18 302 查看
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct node
{
int data;
node *next;
};

class listt
{
private:
node *Head;
public:
void creat();
void display();
void Insert(int i,int x);
int Delete(int i);
};

void listt::Insert(int i,int x)
{
node *p,*q,*s;
int k=1;
q=Head;
p=Head->next;
while(k<i&&p!=NULL)
{
q=p;
p=p->next;
k++;
}
if(k==i)
{
s=new node;
s->data=x;
q->next=s;
s->next=p;
cout<<"插入成功"<<endl;
}
else
cout<<" 插入失败"<<endl;
}

void listt::creat()
{
node *last,*p;
int num;
Head=last=NULL;
scanf("%d",&num);
while(num>0)
{
p=(node *) malloc(sizeof(node));
p->data=num;
p->next=NULL;
if(Head==NULL)
Head=p;
else
last->next=p;
last=p;
scanf("%d",&num);
}
}

void listt::display()
{
node *p;
if(Head!=NULL)
{
p=Head;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
else
cout<<"空表"<<endl;
return ;
}

int listt::Delete(int i)
{
node *p,*q,*s;
int x,k=1;
q=Head;
p=Head->next;
while(k<i&&p!=NULL)
{
q=p;
p=p->next;
k++;
}
if(p!=NULL)
{
x=p->data;
q->next=p->next;
printf("删除成功\n");
}
else
{
printf("删除失败\n");
x=-1;
}
return x;
}

int main()
{

listt A;
A.creat();
int m,n,v;
printf("输入你想插入的位置和插入的数,用空格隔开\n");
cin>>m>>n;
A.Insert(m,n);
printf("输入你想删除的位置\n");
cin>>v;
A.Delete(v);
A.display();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: