数据结构实验一:(2)(单链表)线性表的各种操作LinkList

 

 

 

 

 

 

 

 

 

 

代码:

#include<iostream>
#include<malloc.h>
#include<cstdio>
using namespace std;
typedef struct LNode
{
    char data;
    struct LNode*next;
}LinkNode;

void InitList(LinkNode *& L){
    L=(LinkNode*)malloc(sizeof(LinkNode));
    L->next=NULL;
}

bool InsertList(LinkNode*& L,int i,char e){
    int j=0;
    LinkNode *p=L,*s;
    if(i<=0) return false;
    while (j<i-1&&p!=NULL){
        j++;
        p=p->next;
    }
    if(p==NULL)
        return false;
    else{
        s=(LinkNode*)malloc(sizeof(LinkNode));
        s->data=e;
        s->next=p->next;
        p->next=s;
        return true;
    }
}

void DispList (LinkNode *L){
    LinkNode *p=L->next;
    while(p!=NULL){
        printf("%c",p->data);
        p=p->next;
    }
    printf("\n");
}

int LengthList(LinkNode*L){
    int n =0;
    LinkNode *p=L;
    while(p->next!=NULL){
        n++;
        p=p->next;
    }
    return n;
}

bool EmptyList(LinkNode* L){
    return(L->next==NULL);
}

char GetElem(LinkNode *L,int i){
    int j=0;
    char e;
    LinkNode*p=L;
    if(i>0){
        while(j<i&&p!=NULL){
            j++;
            p=p->next;
        }
        if(p!=NULL)
            e=p->data;
    }
    return e;
}

int LocateElem(LinkNode*&L,char e){
    int i=1;
    LinkNode *p=L->next;
    while(p!=NULL&&p->data!=e){
        p=p->next;
        i++;
    }
    if(p==NULL)
        return 0;
    else
        return i;
}
bool DeleteList(LinkNode *&L,int i,char &e){
    int j=0;
    LinkNode *p=L,*q;
    while(j<i-1&&p->next!=NULL){
        j++;
        p=p->next;
    }
    if(p==NULL)
        return false;
    else{
        q=p->next;
        if(q==NULL)
            return false;
        e=q->data;
        p->next=q->next;
        free(q);
        return true;
    }

}

void DestroyList(LinkNode*& L){
    LinkNode *p=L,*s=L->next;
    while(s!=NULL){
        free(s);
        p=s;
        s=s->next;
    }
    free(p);
}


int main (){
    LinkNode *L;
    char e;
    int i;
    InitList(L);
    InsertList(L,1,'a');
    InsertList(L,2,'b');
    InsertList(L,3,'c');
    InsertList(L,4,'d');
    InsertList(L,5,'e');
    DispList(L);
    printf("%d",LengthList(L));
    printf("\n");
    if(EmptyList(L)==true)
        printf("yes");
    else
        printf("no");
    printf("\n");
    printf("%c",GetElem(L,3));
    printf("\n");
    printf("%d",LocateElem(L, 'a'));
    printf("\n");
    InsertList(L,4,'f');
    DispList(L);
    DeleteList(L,3,e);
    DispList(L);
    DestroyList(L);
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值