带头节点单链表操作

来源:互联网 发布:经传证券炒股软件 编辑:程序博客网 时间:2024/05/03 05:34
#include <iostream>#include <cstdio>#include <cstdlib>using namespace std;typedef long long LL;typedef struct Node{    int data;    struct Node *next;}*List;//头插法建立长为n的链表void FrontCreateList(List &L,int n){    List p;    L=(Node*)malloc(sizeof(Node));    L->next=NULL;    for(int i=0;i<n;i++){        p=(Node*)malloc(sizeof(Node));        cin>>p->data;        p->next=L->next;        L->next=p;    }}//尾插法建立长为n的链表void EndCreateList(List &L,int n){    List p,q;    L=(Node*)malloc(sizeof(Node));    L->next=NULL;    for(int i=0;i<n;i++){        p=(Node*)malloc(sizeof(Node));        cin>>p->data;        p->next=NULL;        if(L->next==NULL)            L->next=p;        else            q->next=p;        q=p;    }}//销毁链表void Destroy(List &L){    List p;    while(L){        p=L->next;        free(L);        L=p;    }    cout<<"OK"<<endl;}//清空链表void Clear(List L){    List p=L->next;    L->next=NULL;    Destroy(p);}//判断链表是否为空bool IsEmpty(List L){    if(L->next==NULL)        return 1;    else        return 0;}//返回链表的长度int Length(List L){    int j=0;    List p=L->next;    while(p){        j++;        p=p->next;    }    return j;}//查找值是否存在int GetData(List L,int i,int *e){    int j=0;    List p=L->next;    while(p&&j<i){        j++;        p=p->next;    }    if(!p||i<1)        return false;    *e=p->data;    return true;}//得到值的位置int LocateData(List L,int e){    int j=0;    List p=L->next;    while(p){        j++;        if(p->data==e)            return j;        p=p->next;    }    return false;}//在第i的位置插入evoid Insert(List L,int i,int e){    int j=0;    List p=L,q,s;    while(p&&j<i-1){        j++;        p=p->next;    }    if(!p||i<1)        exit(0);    q=p->next;    s=(Node *)malloc(sizeof(Node));    if(!s)        exit(-1);    s->data=e;    s->next=q;    p->next=s;}//删除第i位置的节点,并用e返回void Delete(List L,int i,int *e){    int j=0;    List p=L,q;    while(p&&j<i-1){        j++;        p=p->next;    }    if(!p||i<1)        exit(-1);    q=p->next;    *e=q->data;    p->next=q->next;    free(q);}//从头遍历链表void Travel(List L){    List p=L->next;    while(p){        cout<<p->data<<" ";        p=p->next;    }    cout<<endl;}//测试int main(){    int n;    cin>>n;    List L;    EndCreateList(L,n);    Travel(L);    cout<<Length(L)<<endl<<endl;    int out,i;    cin>>i;    Delete(L,i,&out);    cout<<out<<endl;    Travel(L);    cout<<Length(L)<<endl<<endl;    int j,put;    cin>>j>>put;    Insert(L,j,put);    Travel(L);    cout<<Length(L)<<endl<<endl;    int sear;    cin>>sear;    cout<<LocateData(L,sear)<<endl<<endl;    cout<<IsEmpty(L)<<endl;    Destroy(L);    return 0;}
原创粉丝点击