单链表的基本操做(头插入建表)

#ifndef EMPLOYEE_H_INCLUDED
#define EMPLOYEE_H_INCLUDED

typedef struct employee{
    unsigned int primary;//主键
    unsigned char age;//年龄
    char department[32];//部门名称
    char name[15];//员工姓名
    char mobile[12];//员工手机号
    struct employee * next;//下一条记录
}EMPLOYEE,*PT_EMPLOYEE;

#endif // EMPLOYEE_H_INCLUDED

头文件,结构体的定义node

#include <stdio.h>
#include <stdlib.h>
#include "employee.h"
/*头插入法建表*/
PT_EMPLOYEE insert_node(PT_EMPLOYEE head_node,PT_EMPLOYEE new_node)
{
    if(head_node)
    {
        new_node->next=head_node;
    }
    head_node=new_node;
    return head_node;
}


/*按主键键删除节点*/
PT_EMPLOYEE remove_node(PT_EMPLOYEE head_node,int primary_value){
    PT_EMPLOYEE iterator=head_node;
    PT_EMPLOYEE temp=0;
    if(head_node->primaty==primary_value)
    {
        printf("%d\n\n\n\n\n\n\n",head_node->primaty);
        head_node=iterator->next;
        free(iterator);
    }
    else
    {
        while(iterator&&iterator->next){
            temp=iterator->next;
            if((temp->primaty)==primary_value)
            {
                printf("%d\n\n\n\n\n\n\n",temp->primaty);
                iterator->next=temp->next;
                free(temp);
                break;
            }
            else{
                iterator=iterator->next;
            }
        }
    }
    return head_node;
}

/*计算节点个数*/
int count_node(PT_EMPLOYEE head)
{
    PT_EMPLOYEE iterator=head;
    int i=0;
    while(iterator){
        ++i;
        iterator=iterator->next;
    }
    return i;
}

/*打印单链表所有内容*/
int show_list(PT_EMPLOYEE head_node)
{
    PT_EMPLOYEE iterator=head_node;
    while(iterator){
        printf("员工工号:%d\n",iterator->primaty);
        printf("员工姓名:%s\n",iterator->name);
        printf("部门名称:%s\n",iterator->department);
        printf("员工年龄:%d\n",iterator->age);
        printf("手机号码: %s\n\n",iterator->mobile);
        iterator=iterator->next;
    }
    return 0;
}

/*清除全部节点*/
PT_EMPLOYEE clean_list(PT_EMPLOYEE head)
{
    PT_EMPLOYEE iterator=head;
    while(iterator){
        head=head->next;
        free(iterator);
        iterator=head;
    }
    return head;
}

/*主函数*/
int main(void)
{

    PT_EMPLOYEE emlist=0;
    PT_EMPLOYEE new_node=0;
    int i=1,count=0;
    for(i=1;i<10;++i){
        new_node=malloc(sizeof(EMPLOYEE));
        new_node->age=i;
        new_node->primaty=i;
        sprintf(new_node->department,"%s%d","部门",i);
        sprintf(new_node->name,"%s%d","员工",i);
        sprintf(new_node->mobile,"%s","88888888888");
        new_node->next=0;
        emlist=insert_node(emlist,new_node);
    }
   
    emlist=remove_node(emlist,5);
    emlist=remove_node(emlist,1);
    emlist=remove_node(emlist,9);
    emlist=remove_node(emlist,6);
    
    count=count_node(emlist);
    printf("链表长度:%d\n",count);
    show_list(emlist);
    emlist=clean_list(emlist);
    printf("清空之后");
    show_list(emlist);
    return 0;
}

主要逻辑实现函数

相关文章
相关标签/搜索