zoukankan      html  css  js  c++  java
  • linux c语言链表的简单应用之删除链表

    /* ************************************************************************
    * Filename: link.c
    * Description:
    * Version: 1.0
    * Created: 2011骞?4鏈?9鏃?17鏃?2鍒?3绉?
    * Revision: none
    * Compiler: gcc
    * Author: wen hao (WH), hnrain1004@gmail.com
    * Company: sunplusapp
    * ***********************************************************************
    */


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

    #define LEN sizeof(struct stu)
    //声明结构体
    typedef struct stu
    {
    int num;
    char name[10];
    struct stu *next;
    }TYPE;

    //链表创建函数,返回类型为结构体指针类型
    TYPE * create(int n)
    {
    TYPE
    *head,*prev,*curre;
    int i;

    for(i = 0; i < n; i++)
    {
    curre
    = (TYPE *)malloc(LEN);//申请空间
    printf("input number and name:\n");
    scanf(
    "%d %s",&curre->num,curre->name);//等待用户输入数据

    if(i == 0)
    prev
    =head=curre;
    else
    prev
    ->next=curre;
    prev
    =curre;
    }
    curre
    ->next =NULL;
    return head;
    }

    TYPE
    * delete(TYPE *head,int num)
    {
    TYPE
    *prev,*curre;

    if(NULL == head)//如果链表为空
    {
    printf(
    "the link is empty!\n");
    goto end;
    }

    curre
    = head;//如果不为空,让curre指向head

    while(curre->num != num && curre->next != NULL)//遍历查找数据,并且确定不是最后一个数据
    {
    prev
    = curre;//让prev指向当前指针
    curre = curre->next;//让curre指向下一个数据
    }
    if(curre->num == num)
    {
    if(curre == head)//如果是第一个数据
    {
    head
    = curre->next;
    }
    else
    {
    prev
    ->next = curre->next;//让前一个数据指向下一个数据
    }
    free(curre);
    //记得释放空间
    printf("the node %d is deleted\n",num);//显示删掉了第几个数据
    }
    printf(
    "in the link no this data\n");
    end:
    return head;
    }


    //打印输出函数,形参为链表头指针
    void print(TYPE *head)
    {
    printf(
    "\nthe link message is :\n");
    printf(
    "number \t\tname \n");
    while(head!=NULL)//如果没有指向链表尾就一直打印
    {
    printf(
    "%d\t\t%s\n",head->num,head->name);
    head
    =head->next;
    }
    printf(
    "\n");
    }

    int main(void)
    {
    TYPE
    *head;//定义结构体变量
    head = create(3);//创建链表
    print(head);//打印链表
    printf("----------delete----------\n");
    delete(head,
    2);//删除编号为2的数据
    print(head);//打印删除后的链表

    return 0;
    }
  • 相关阅读:
    升级salt导致进程kill问题记录
    记一次centos6升级salt-minion启动失败的问题
    3.ElasticSearch的倒排索引
    4.ElasticSearch的基本api操作
    1.ElasticSearch介绍及基本概念
    10.openldap备份与恢复
    1.Python3.6环境部署
    8.openldap mirrormode(主主同步)
    7.openldap使用ssl加密认证
    Python json解析
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2033039.html
Copyright © 2011-2022 走看看