用c++写的链表

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值