Chinaunix首页 | 论坛 | 博客
  • 博客访问: 25049
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 45
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-22 19:19
文章分类
文章存档

2019年(1)

2018年(1)

2017年(2)

我的朋友

分类: C/C++

2017-07-28 23:22:55

/*单链表的头插法和尾插法c语言实现*/
记录一下单链表的插入操作,比较简单的数据存储结构但却很实用。

#include
#include
#include
#define SIZE 100
/*简单的定义一个链表节点的数据单元*/
typedef struct student_t
{
int num;
char name[SIZE];
struct student_t* pNext;
}studentList, *pStudentList;


/*定义一个全局的静态的链表头节点指针*/
static pStudentList g_pstStudentList = NULL;


/*创建一个学生信息的链表节点*/
pStudentList createaOneStudentListNode()
{
pStudentList pNewNode = NULL;
pNewNode = (pStudentList)malloc(sizeof(studentList));
return pNewNode;
}
/*在链表头插入数据节点*/
int addOneStudentToListHead(int num, char* name)
{
pStudentList pNewNode = NULL;
int result = 0;


if ((num < 0) || (name == NULL))
{
result = -1;
printf("error inoput parameter!\n");
return result;
}
pNewNode = createaOneStudentListNode();
pNewNode->num = num;
memcpy(pNewNode->name, name, strlen(name));
pNewNode->pNext = g_pstStudentList;
g_pstStudentList = pNewNode;
return result;
}
/*在链表尾部插入数据节点*/
int addOneStudentToListTail(int num, char* name)
{
pStudentList pTempHead = NULL;
pStudentList pTailNode = NULL;
pStudentList pNewNode = NULL;
int result = 0;


if ((num < 0) || (name == NULL))
{
result = -1;
printf("error input parameter!\n");
return result;
}
pTempHead = g_pstStudentList;
while(pTempHead)
{
if (pTempHead->pNext == NULL)
{
pTailNode = pTempHead;
}
pTempHead = pTempHead->pNext;

}
pNewNode = createaOneStudentListNode();
pNewNode->num = num;
memcpy(pNewNode->name, name, strlen(name));
pNewNode->pNext = NULL;
pTailNode->pNext = pNewNode;
return result;
}
/*输出整个链表中的学号信息,检查插入的是否正确,插入时没有考虑是否有相同学号*/
void printList()
{
pStudentList pTempHead = NULL;
pTempHead = g_pstStudentList;
while(pTempHead)
{
printf("studnet num = %d\n", pTempHead->num);
pTempHead = pTempHead->pNext;
}
}
/*释放整个链表的资源*/
void freeList()
{
pStudentList pTempHead = NULL;
pStudentList pFree = NULL;
int i = 0;
pTempHead = g_pstStudentList;
pFree = g_pstStudentList;


while(pTempHead)
{
pFree = pTempHead;
printf("free studnet num = %d\n", pTempHead->num);
pTempHead = pTempHead->pNext;
if (pFree != NULL)
{
printf("i = %d\n", i);/*测试是否正确释放资源*/
free(pFree);
}
++i;
}
}
int main()
{
/*构建头节点*/
char* cName = "allan";
g_pstStudentList = createaOneStudentListNode();
g_pstStudentList->num = 0;
memcpy(g_pstStudentList->name, cName, strlen(cName));
g_pstStudentList->pNext = NULL;


/*使用尾插法插入数据*/
char* cName1 = "allan1";
addOneStudentToListTail(1,cName1);


/*使用尾插法插入数据*/
char* cName2 = "allan2";
addOneStudentToListTail(2,cName2);


/*使用头插法插入数据*/
char* cName3 = "allan3";
addOneStudentToListHead(3,cName3);


/*输出当前链表中存储的学号,没有考虑学号的唯一性,假设输入的都是不同数字*/
printList();


/*使用完资源后进行释放资源,防止内存泄漏*/
freeList();
return 0;
}
程序在VS2008上运行结果如图所示:

阅读(1633) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~