c语言 linked list

本文介绍了一种使用C语言实现的简单链表结构,并详细解释了链表的创建、遍历和删除节点的基本操作。通过实例演示,帮助读者理解链表的基本概念和在实际编程中的应用。

MyLinkList.h

#include <stdlib.h>
#include <string.h>
#define  NEW  (struct node *)malloc(sizeof(struct node))

struct node
{
    char name[20];
    char tel[9];
    struct  node *next;
};

/* 创建 linked list   */

struct node *create()
{
    static struct node *h;
    struct node *p,*q;
    char name[20];
    h = NULL;
    printf("name : ");
    gets(name);
    while(0 != strlen(name))
    {
        p = NEW;
        if(NULL == p)
        {
            printf("allocation failure \n");
            exit(0);
        }
        strcpy(p->name,name);
        printf("tel : ");
        gets(p->tel);
        p->next = NULL;
        if(NULL == h)
            h = p;
        else
            q->next = p;
        q = p;
        printf("name: ");
        gets(name);
    }
    return h;
}

/* 遍历linked list   */

void printlist(struct node *head)
{
    struct node *p;
    p = head;
    while(NULL != p)
    {
        printf("%s\t%s\n",p->name,p->tel);
        p = p->next;

    }

}

/* 删除节点   */

struct node *delnode(struct node *head, char *x)
{
    struct node *p,*q;
    static struct node *h;
    if(NULL == head)
    {
        printf("this is a empty linked list");
        return head;
    }
    p = head;
    while(0 != strcmp(x,p->name) && NULL != p->next)
    {
        q = p;
        p = p->next;
    }
    if(0 == strcmp(x,p->name))
    {
        if( p == head)
            head = p->next;
        else
            q->next = p->next;
        free(p);
    }
    else
        printf("can't find your node");
    h = head;
    return h;
}


main.c


#include <stdio.h>
#include "MyLinkList.h"



int main(void)
{
    struct node *head;
    head = create();

    printf("-----------遍历测试-----------------\n");

    printlist(head);

     printf("---------删除测试-------------\n");

     char *delchar[20];
     gets(delchar);
     delnode(head,delchar);
     printlist(head);
     printf("-------------------------------\n");




     printf("-------------------------------\n");





     printf("-------------------------------\n");



}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值