数据结构单链表基本功能c++实现

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 1005
using namespace std;
typedef int T;
template<class T>
struct node
{
    int data;
    node <int> *next;
};
class LinkList
{public:
    LinkList();
    LinkList(int a[],int n);
    ~LinkList();
    int Length();
    int Get(int i);
    int Locate(int i);
    void Insert(int i,int x);
    int Delete(int i);
    void PrintList();
private:
    node<int>*first;

};
void LinkList::PrintList()//输出链表
{node<int>*p;
    p=first->next;
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}
int LinkList::Length()//长度
{node<int>*p;
    p=first->next;
    int count=0;
    while(p)
    {
        count++;
        p=p->next;
    }
    return count;
}

LinkList::LinkList()//无参构造函数
{
    first=new node<int>;
    first->next=NULL;

}
int LinkList::Get(int i)//按位查找
{
    node<int>*p;
    p=first->next;
    int count=1;
    while(p&&count<i)
    {

        p=p->next;
        count++;
    }
    if(p==NULL)
    throw "位置";
    else
        return p->data;


}
int LinkList::Locate(int x)//按值查找
{
    node<int>*p;
    p=first->next;
    int count=1;
    while(p)
    {if(p->data==x)
    break;
        p=p->next;
        count++;
    }
    return count;
}
void LinkList::Insert(int i,int x)//插入
{
    node<int>*p;
    node<int>*s;
    p=first;
    int count=0;
    while(p&&count<i-1)
    {
        p=p->next;
        count++;
    }
    if(p==NULL)
        throw "位置";
    else
        {s=new node<int>;
        s->data=x;
         s->next=p->next;
         p->next=s;
        }
}
int LinkList::Delete(int i)//删除
{
    node<int>*p;
    node<int>*s;
    node<int>*q;
    int x;
    int count=0;
    p=first;
    while(p!=NULL&&count<i-1)
    {
        p=p->next;
        count++;
    }
    if(p==NULL||p->next==NULL)
    throw"位置";
    else
    {q=p->next;
    x=q->data;
        p->next=q->next;
        delete q;
    }
    return x;

}
/*LinkList::LinkList(int a[],int n)//头插法构造
{
    first=new node<int>;
    first->next=NULL;
    node<int>*s;
    for(int i=0;i<n;i++)
    {
        s=new node<int>;
        s->data=a[i];
        s->next=first->next;
        first->next=s;
    }
}*/
LinkList::LinkList(int a[],int n)//尾插法构造
{
    node<int>*r;
    first=new node<int>;
    r=first;
    node<int>*s;
    for(int i=0;i<n;i++)
    {
        s=new node<int>;
        s->data=a[i];
        r->next=s;
        r=s;
    }
    r->next=NULL;
}
LinkList::~LinkList()//析构函数
{
node<int>*q;
while(first!=NULL)
{
    q=first;
    first=first->next;
    delete q;
}

}
int main()

{
  int a[5]={1,2,3,4,5};
  LinkList l=LinkList();
  l=LinkList(a,5);
  cout<<l.Length()<<endl;
l.PrintList();
cout<<l.Get(2)<<endl;
cout<<l.Locate(3)<<endl;
l.Insert(2,100);
l.PrintList();
cout<<l.Delete(2)<<endl;
l.PrintList();
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/88524428