您的位置:首页 > 编程语言 > C语言/C++

C++ 实现链表的基本操作之一:链表插入

2012-07-25 23:06 846 查看
用C++语言实现链表基本操作:

一、链表定义及相关操作声明 LinkList.h 文件

1.链表定义

typedef struct staff_listnode StructStaffNode;

struct staff_listnode
{
string name; // 员工姓名
int age; //员工年龄
bool sex; //员工性别
string number; //员工工号
string entrydate; //员工入职日期
StructStaffNode *next; //单链表指针
}; 2.链表相关操作 //创建一个新的链表节点
StructStaffNode * LinkList_CreateNewNode(void); //打印链表内容
void LinkList_PrintNode(StructStaffNode *pSNode); //链表中插入一个结点.
void LinkList_StaffInsert(StructStaffNode *psNewStaff);

二、链表相关操作的实现 (LinkList.cpp 文件)

/*
/*
* 单链表相关操作的实现
*/
//需要包含的头文件
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "SLinkList.h" //#define DEBUG_LINKLIST /*************************************
*全局数据定义
**************************************/ StructStaffNode *pStaff_List; /*
* 函数名:LinkList_CreateNewNode
* 功 能:创建一个新的结构体节点.
* 参 数:void
* 返回值:StructStaffNode类型的指针.
*/
StructStaffNode *LinkList_CreateNewNode(void)
{
StructStaffNode *head = NULL;
head = new StructStaffNode;
if(NULL == head)
{
#ifdef DEBUG_LINKLIST
printf("Create new linklist node failed.\n");
#endif
assert(0);
}else{
#ifdef DEBUG_LINKLIST
printf("Create new linklist node success.\n");
#endif
}
return head;
} /*
* 函数名:LinkList_PrintNode
* 功 能:打印链表pSNode的所有节点.
* 参 数:
*/
void LinkList_PrintNode(StructStaffNode *pSNode)
{
int NumNode = 0;
while(pSNode)
{
cout <<"这是链表中的第" << NumNode << "个结点"<<endl;
cout <<"员工姓名:"<< pSNode->name <<endl;
if(pSNode->sex)
cout <<"员工性别:男" <<endl;
else
cout << "员工性别:女" <<endl;
cout <<"员工年龄:" << pSNode->age <<endl;
cout << "入职时间:" << pSNode->entrydate <<endl;
cout << "员工工号:" << pSNode->number <<endl;
cout <<"-------------------华丽分割线-----------------------"<<endl; NumNode++;
pSNode=pSNode->next;
}
} void LinkList_StaffInsert(StructStaffNode *psNewStaff)
{
//用于查找全局单链表的尾指针;
StructStaffNode *tail = NULL; //如果插入结点为空,直接返回.
if(NULL == psNewStaff)
return; //当结点psNewStaff 不为空时,将其插入到主链表中.
//遍历链表,找到链表尾部.
if(NULL == pStaff_List)
{
pStaff_List = psNewStaff;
}else{
tail = pStaff_List;
while(tail->next)
tail = tail->next; tail->next = psNewStaff;
}
psNewStaff->next = NULL;
} 三、测试程序 main.cpp /*
*单链表操作测试主程序
*/ #include <stdio.h>
#include <stdlib.h>
#include "SLinkList.h" extern StructStaffNode *pStaff_List; /*************************************
*全局数据定义
**************************************/
#define MAN 1
#define FEMALE 0 //main函数
void main(void)
{
for(int i=0; i < 5; i++)
{
StructStaffNode *myStaff = NULL;
myStaff = LinkList_CreateNewNode();
if(NULL != myStaff)
{
myStaff->name = "张三";
myStaff->age = 28;
myStaff->entrydate = "2011-01-17";
myStaff->sex = MAN;
myStaff->number = "110812426";
myStaff->next = NULL; LinkList_StaffInsert(myStaff);
}
}
LinkList_PrintNode(pStaff_List);
system("pause");
return;
} 本段程序输出结果为:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐