用c++写的链表

来源:互联网 发布:淘宝招儿童平面小模特 编辑:程序博客网 时间:2024/05/17 03:12
#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;}

0 0