完整单链表程序

本文采用插入采用头插法,删除采用任意位置删除。

什么是链表:链表就是结构体变量与结构体变量通过指针连接在一起。

单链表主要是数据域和指针域构成。

单链表的编程思路:动态内存申请+模块化设计

1.动态内存申请就是为了使得结构体指针变为结构体变量。

2.模块化设计

(1)表头

(2)节点

(3)插入节点

(4)删除节点

(5)打印遍历链表

下面直接展示完整程序:

#include"stdio.h"
#include"stdlib.h"

struct node
{
    int data;
    struct node* next;
};

struct node* createlist()
{
    struct node* headnode = (struct node*)malloc(sizeof(struct node));
    headnode->next = NULL;
    return headnode;
}

struct node* createnode(int data)
{
    struct node* newnode = (struct node*)malloc(sizeof(struct node));
    newnode->data = data;
    newnode->next = NULL;
    return newnode;
}

void printlist(struct node* headnode)
{
    struct node* pmove = headnode->next;
    while(pmove)
    {
        printf("%d\t",pmove->data);
        pmove = pmove->next;
        
    }
        printf("\n");
}
void insernodebyhead(struct node* headnode,int data)
{
    struct node* newnode = createnode(data);
    newnode->next = headnode->next;
    headnode->next = newnode;
}

void deletenodebyappoin(struct node* headnode,int posdata)
{
    struct node* posnode = headnode ->next;
    struct node* posnodefront = headnode;
    if(posnode==NULL)
    printf("无法删除\n");
    else
    {
        while(posnode->data !=posdata)
        {
            posnodefront=posnode;
            posnode=posnodefront->next;
            if(posnode==NULL)
            {
                printf("没有找到相关信息,无法删除\n");
                break;
                
            }
            
        }
                posnodefront->next=posnode->next;
                free(posnode);
    }
}

int main()
{
    struct node* list=createlist();
    insernodebyhead(list,1);
    insernodebyhead(list,2);
    insernodebyhead(list,3);
    printlist(list);
    deletenodebyappoin(list,1);
    printlist(list);
   // system("pause");
    return 0;
}
            
            

最后实现结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值