/*单链表的头插法和尾插法c语言实现*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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;
}