数据结构复习整理——线性表链式存储的基本操作

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;


typedef int ElemType;
struct LNode
{
    ElemType data;
    struct LNode *next;
};
//链表的建立
struct LNode* Build(struct LNode *head)
{
    struct LNode *p,*q;
    p=q=(struct LNode*)malloc(sizeof(struct LNode));
    p->next=NULL;
    int i=1;
    while(i<=11)
    {
        if(head==NULL)
            head=p;
        else
            q->next=p;
        q=p;
        p=(struct LNode*)malloc(sizeof(struct LNode));
        p->data=i;
        i++;
    }
    free(p);
    p=NULL;
    q->next=NULL;
    return head;
}




//链表的插入,其中i表示第i个数,m表示要插入的字符
struct LNode* LNode_insert(struct LNode *head,int i,ElemType n)
{
    int j=1;
    struct LNode *p1,*p2;
    p1=(struct LNode*)malloc(sizeof(struct LNode));
    p1=head;
    while(p1&&j<i)
    {
        p1=p1->next;
        j++;
    }
    p2=(struct LNode*)malloc(sizeof(struct LNode));
    p2->data=n;
    p2->next=p1->next;
    p1->next=p2;
    return head;
}
//链表的删除,其中j表示第j个数
struct LNode* LNode_delete(struct LNode *head,int i)
{
    int j=1;
    struct LNode *p,*q;
    p=head;
    while(p&&j<i)
    {
        p=p->next;
        j++;
    }
    q=p->next;
    p->next=p->next->next;
    free(q);
    return head;
}
//链表的遍历
void print(struct LNode *head)
{
    ElemType m;
    struct LNode *p;
    p=head;
    while(p->next!=NULL)
    {
        p=p->next;
        m=p->data;
        cout<<m<<" ";
    }
}
int main()
{
    int i,k,n;
    struct LNode *head;
    head=NULL;
    head=Build(head);
    print(head);
    cout<<endl;
    cout<<"请输入你要插入数的位置i和数值n;";
    cout<<endl;
    cin>>i>>n;
    head=LNode_insert(head,i,n);
    cout<<"插入后的结果为:";
    print(head);
    cout<<endl;
    cout<<"请输入你要删除数的位置i;";
    cout<<endl;
    cin>>k;
    head=LNode_delete(head,k);
    cout<<"删除后的结果为:";
    print(head);
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值