基本操作:链表插入

2020年1月17日 1076点热度 0人点赞 0条评论

基本操作:链表插入

时间: 1ms        内存:128M

描述:

实现链表的插入操作 bool ListInsert(LinkList *&L,int i,ElemType e) 在链表L的第i个位置插入数据元素e(i从1开始)。 假设顺序表的元素类型为char,主函数及其他函数已给出。

#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct LNode //定义单链表结点类型
{
    ElemType data;
    struct LNode *next;
} LinkList;
void InitList(LinkList *&L)  //初始化线性表
{
    L=(LinkList *)malloc(sizeof(LinkList));   //创建头结点
    L->next=NULL;
}
void DestroyList(LinkList *&L) //销毁线性表
{
    LinkList *p=L,*q=p->next;
    while (q!=NULL)
    {
        free(p);
        p=q;
        q=p->next;
    }
    free(p);
}
bool ListEmpty(LinkList *L) //判线性表是否为空表
{
    return(L->next==NULL);
}
int ListLength(LinkList *L) //求线性表的长度
{
    LinkList *p=L;
    int i=0;
    while (p->next!=NULL)
    {
        i++;
        p=p->next;
    }
    return(i);
}
void DispList(LinkList *L) //输出线性表
{
    LinkList *p=L->next;
    while (p!=NULL)
    {
        printf("%c ",p->data);
        p=p->next;
    }
    printf("\n");
}

int main()
{
    ElemType a,b,c,d,e,f;
    LinkList *h;
    InitList(h);
    printf("依次采用尾插法插入a,b,c,d,e元素\n");
    scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e);
    ListInsert(h,1,a);
    ListInsert(h,2,b);
    ListInsert(h,3,c);
    ListInsert(h,4,d);
    ListInsert(h,5,e);
    DispList(h);
    printf("单链表h长度=%d\n",ListLength(h));
    printf("在第4个元素位置上插入f元素\n");
    scanf("%c",&f);
    ListInsert(h,4,f);
    DispList(h);
    DestroyList(h);
    return 0;
}

注意:只提交bool ListInsert(LinkList *&L,int i,ElemType e)部分。

输入:

输入生成链表的5个元素a,b,c,d,e

输入插入链表第4个位置的元素f

输出:

输出链表长度

输出插入操作后的链表

示例输入:

1 3 5 7 9
6

示例输出:

依次采用尾插法插入a,b,c,d,e元素
1 3 5 7 9 
单链表h长度=5
在第4个元素位置上插入f元素
1 3 5 6 7 9 

提示:

参考答案:

解锁文章

没有看到答案?微信扫描二维码可免费解锁文章

微信扫描二维码解锁

使用微信扫描二维码打开广告页面后可以立即关闭,再刷新此页面即可正常浏览此文章

所跳转广告均由第三方提供,并不代表本站观点!

已经扫描此二维码?点此立即跳转

code

这个人很懒,什么都没留下

文章评论