링크 및 그 작업 의 실현

18900 단어 데이터 구조
#include 
#include 
#include 
using namespace std;
typedef char ElemType;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;
int ListLength(LinkList L);
ElemType GetElem(LinkList L,int i);
void InsertList(LinkList &L,ElemType x,int i);
int DeleteElem (LinkList &L,int i);
void DisplayList(LinkList L);
LinkList LA;
int main()
{
    LA=NULL;
    ElemType cs;
    int len=0;
  //  scanf("%s",&LA);
    InsertList(LA,'a',1);
    InsertList(LA,'B',2);
    InsertList(LA,'C',2);
    cs=GetElem(LA,3);

    cout<<cs<<endl;
    cout<<ListLength(LA)<<endl;
    DisplayList(LA);
    DeleteElem(LA,2);
    DisplayList(LA);
    return 0;
}
int ListLength(LinkList L)
{
    //cout<
    int n=0;
    struct LNode *q=L;
    if(L==NULL)
        cout<<"    "<<endl;
    while(q!=NULL)
    {
        n++;
        q=q->next;
    }
    return n;
}

ElemType GetElem(LinkList L,int i)
{
    //cout<
    int j=1;
    struct LNode *q=L;
    while(j<i&&q!=NULL)
    {
        q=q->next;
        j++;
    }
    if(q!=NULL) return (q->data);
    else
        cout<<"       !"<<endl;
    return 0;
}
void InsertList(LinkList &L,ElemType x,int i)
{
    //cout<
    int j=1;
    struct LNode *s,*q;
    s=new LNode ;
    s->data=x;
    q=L;
    if(i==1)
    {
        s->next=q;
        L=s;

    }
    else
    {
        while(j<i-1&&q->next!=NULL)
        {
            q=q->next;
            j++;
        }
        if(j==i-1)
        {
            s->next=q->next;
            q->next=s;
        }
    }

}
int DeleteElem (LinkList &L,int i)
{
    //cout<
    int j=1;
    struct LNode *q=L,*t;
    if(i==1)
    {
        t=q;
        q=q->next;
    }
    else
    {
        while(j<i-1&&q->next!=NULL)
        {
            j++;
            q=q->next;
        }
        if(q->next!=NULL&&j==i-1)
        {
            t=q->next;
            q->next=t->next;
        }
        else
            cout<<"       !"<<endl;

    }
    if(t)
        return t->data;
    return 0;

}

void DisplayList(LinkList L)
{
    struct LNode *q;
    q=L;
    cout<<"    ";
    if(q==NULL)
        cout<<"    "<<endl;
    else if(q->next==NULL)
        cout<<q->data<<".";
    else
    {
        while(q->next!=NULL)
        {
            cout<<q->data<<" ";
            q=q->next;
        }
        cout<<q->data<<" ";
    }
    cout<<endl;

}

좋은 웹페이지 즐겨찾기