链表的简单实现

#include <cstdio>
#include <malloc.h>

typedef int ElemType;

typedef struct ListNode
{
    ElemType Element;
    ListNode *next;
} *PNode;

//创建链表
PNode CreateList(void)
{
    int len; // 链表长度
    int val; //存放链表数值
    PNode PHead = (PNode) malloc (sizeof(PNode)); //头结点
    PNode PTail = PHead; //尾节点
    PTail -> next = NULL;
    printf("请输入结点个数\n");
    scanf("%d",&len);
    for (int i = 0; i < len; i++)
    {
        PNode PNew = (PNode) malloc (sizeof(PNode));
        if (PNew == NULL)
        {
            printf("分配新节点失败\n");
            return 0;
        }
        printf ("请输入第%d个节点的数据\n",i);
        scanf("%d",&val);

        PNew -> Element = val;
        PTail -> next = PNew;
        PNew -> next = NULL;
        PTail = PNew;

    }
    printf ("创建链表成功!\n");
    return PHead; //返回头节点
}
//插入元素
void InsertList (PNode p, int pos, int elem)
{
    PNode k = (PNode) malloc (sizeof(PNode));
    PNode q = p;
    for (int i = 0; i< pos - 1; i++)
    {
        q = q->next;
    }
    k ->Element = elem;
    k-> next = q -> next;
    q->next = k;
}
//删除元素
void DeleteList(PNode p, int pos)
{
    PNode q = p;
    for (int i = 0; i < pos - 1; i++)
    {
        q = q ->next;
    }
    q -> next = q -> next ->next;

}
//free链表
void FreeList(PNode p)
{
    int i;
    while(p != NULL)
    {
        free(p);
        p = p->next;
        //printf ("%d\n",i++);
    }
}
void Print (PNode p)
{
    printf ("输出链表的值\n");
    PNode q = p -> next;
    while (q != NULL)
    {
        printf("%d\n",(q -> Element));
        q = q ->next;
        
    }
}

int main()
{
    ElemType data;
    int pos;
    PNode List = CreateList();

    Print(List);
    printf("插入操作,请输入插入的位置和数字\n");
    scanf("%d%d",&pos,&data);
    InsertList(List,pos,data);
    Print (List);
    printf("删除操作,输入删除的位置\n");
    scanf("%d",&pos);
    DeleteList(List,pos);
    Print (List);

    FreeList(List);
    return 0;
}

 输出结果

(对有时间学习编程的人士强烈推荐vscode,界面美观,并且能学到很多底层的东西)

转载于:https://www.cnblogs.com/venray/p/10511082.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值