c链表

本文介绍了温凯老师的链表操作教程,包括链表的创建、插入、删除、打印和释放等基本操作,通过C语言实现,适合初学者学习数据结构和算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

温凯老师数据结构

#include <stdio.h>
#include <stdlib.h>

typedef struct _node
{
    int data;
    struct _node *next;
}Node;

typedef struct _list
{
    Node *head;
}List;
void InsertList(List *list,int num);
void AddListByEnd(List *list,int num);
void AddListByHead(List *list,int num);
void Print(List *list);
void Free(List *list);
int main(void)
{
    List list;
    list.head=NULL;
    int num;
    do
    {
        printf("请输入一个数字:");
        scanf("%d",&num);
        if(num!=-1)
        {
            AddListByEnd(&list,num);
        }
    } while (num != -1);
    Print(&list);
    printf("请输入你要删除的数字:");
    scanf("%d",&num);
    Node *p,*q;
    for(q=NULL,p=list.head;p;q=p,p=p->next)
    {
        if(p->data==num)
        {
            if(q)
            {
                q->next=p->next;
            }
            else
            {
                list.head=p->next;
            }
            
        }
    }
    Print(&list);
    InsertList(&list,5);
    Print(&list);

    system("pause");
    return 0;    
}

void AddListByHead(List *list,int num)
{
    Node *p;
    p=(Node *)malloc(sizeof(Node));
    p->data=num;
    

    if(list->head)
    {
        p->next=list->head;
        list->head=p;
    }
    else
    {
        list->head=p;
        p->next=NULL;
    }
    
}

void Print(List *list)
{
    Node *p;
    for(p=list->head;p;p=p->next)
    {
        printf("%d\n",p->data);
    }
    printf("\n");
}

void Free(List *list)
{
    Node *p,*q;
    for(p=list->head;p;p=q)
    {
        q=p->next;
        free(p);
    }
}

void AddListByEnd(List *list,int num)
{
    Node *p;
    p=(Node *)malloc(sizeof(Node));
    p->data=num;
    static Node *tail;

    if(list->head)
    {
        tail->next=p;
        p->next=NULL;
    }
    else
    {
        list->head=p;
        p->next=NULL;
    }
    tail=p;
    
}

void InsertList(List *list,int num)
{
    Node *current,*previous,*new;
    current=list->head;
    previous=NULL;

    while(current != NULL && current->data <num)
    {
        previous=current;
        current=current->next;
    }

    new=(Node *)malloc(sizeof(Node));

    new->data=num;
    new->next=current;

    if(previous)
    {
        previous->next=new;
    }
    else
    {
        list->head=new;
    }
    


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值