数据结构c++之链表的创建以及各功能的实现

#include <iostream>
using namespace std;
struct node
{
public:
    int data;
    node *next;
};
class Linklist
{
public:
    Linklist(){}
    ~Linklist(){}
    Linklist(int a[],int n);        //利用数组创建一个新的单链表
    int Length();                    //获得链表的长度
    int Get(int i);                     //获取数组中下表为i的数据域
    int Locate(int i);                  //获取数据为i的结点的位置
    void Insert(int i,int x);       //插入元素
    int Delete(int i);                  //删除元素
    void printlist();                   //链表的遍历
private:
    node *head,*p,*t;               //建立头指针,以及两个临时指针
};
Linklist::Linklist(int a[],int n)
{
    head = new node;
    head->next = NULL;
    for(int i=n-1;i>=0;i--)
    {
        p = new node;
        p->data = a[i];         //头插法建立链表
        p->next=head->next;
        head->next = p;
    }
}

int Linklist::Length()
{
    t=head->next;
    int sum=0;
    while(t)
    {
        sum++;
        t=t->next;
    }
    return sum;
}

int Linklist::Get(int i)
{
    t=head->next;
    int sum=0;
    while(t&&sum<i)
    {
        sum++;
        t=t->next;
    }
    return t->data;
}
int Linklist::Locate(int i)
{
    int sum=0;
    t=head->next;
    while(t)
    {
        t=t->next;
        sum++;
        if(i==t->data)
            break;
    }
    return sum;
}
void Linklist::Insert(int i,int x)
{
    p=new node;
    t=head->next;
    int sum=1;
    while(t&&sum<i)
    {
        sum++;
        t=t->next;
    }
    p->data=x;
    p->next=t->next;        //挂链
    t->next=p;                     //摘链
}
int Linklist::Delete(int i)
{
     p=new node;
     t=head->next;
     int sum=1;
     int x;
     while(t&&sum<i)
     {
         sum++;
         t=t->next;
     }
     p=t->next;                 //暂存被删除的结点
     x=p->data;
     t->next=p->next;
     delete p;                      //释放被删除结点的空间
     return x;
}
void Linklist::printlist()
{

    t=head->next;
    while(t)
    {
        cout<<t->data<<" ";
        t=t->next;
    }

}
int main()
{
    int n;
    cout<<"数组的长度为:";
    cin>>n;
    cout<<"请依次输入数组的元素:"<<endl;
    int *a = new int[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    Linklist l(a,n);
    cout<<endl;
    cout<<"数组的长度为:"<<l.Length()<<endl;
    cout<<"下标为4的元素为:"<<l.Get(4)<<endl;
    l.Insert(3,9);
    cout<<"在下标为3处插入元素9:"<<endl;
    l.printlist();
    cout<<endl;
    cout<<"所删除的元素是:"<<l.Delete(3)<<endl;
    cout<<"删除下标为3的元素后:"<<endl;
    l.printlist();


    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值