c语言实现单链表
头文件(声明)
#ifndef LinkList_h
#define LinkList_h
typedef int DataType; //定义节点内数据类型
typedef struct Node
{
DataType data;
struct Node* next;
}Node,*pNode, List, *pList;
void InitLinkList(pList* pplist); //链表初始化
void DestroyLinkList(pList* pplist); //链表销毁
void PushBack(pList* pplist, DataType d);//尾插
void PrintLinkList(pList plist); //打印链表
void PrintTailtoHead(pList plist); //从尾到头打印链表
pNode FindNode(pList plist, DataType d);//寻找节点
void InsertFront(pNode node, DataType d);//在某节点前插入元素
void InversionList(pList* plist); //反转链表
pNode GetEndNode(pList plist); //得到尾节点地址
源文件(定义)
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "LinkList.h"
void InitLinkList(pList* pplist)
{
*pplist = NULL;
}
void DestroyLinkList(pList* pplist)
{
if (*pplist == NULL)
{
return;
}
if ((*pplist)->next == NULL)
{
free(*pplist);
*pplist = NULL;
return;
}
pNode delete = *pplist;
pNode cur = delete->next;
while (cur != NULL)
{
free(delete);
delete = cur;
cur = cur->next;
}
*pplist = NULL;
}
pNode BuyNode()
{
pNode p = malloc(sizeof(Node));
if (p!=NULL)
{
p->next = NULL;
}
return p;
}
void PushBack(pList* pplist, DataType d)
{
if (*pplist == NULL)
{
*pplist = BuyNode();
(*pplist)->data = d;
}
else
{
pNode pre = *pplist;
while (pre->next != NULL)
{
pre = pre->next;
}
pre->next = BuyNode();
pre->next->data = d;
}
}
void PrintLinkList(pList plist)
{
if (plist == NULL)
{
printf("no list");
}
else
{
pNode pre = plist;
while (pre)
{
printf("%d\t",pre->data);
pre = pre->next;
}
}
}
void PrintTailtoHead(pList plist)
{
if (plist == NULL)
return;
else{
PrintTailtoHead(plist->next);
printf("%d\t",plist->data);
}
}
pNode FindNode(pList plist, DataType d)
{
if (plist==NULL) {
printf("空链表\n");
}
pNode pre = plist;
while (pre!=NULL)
{
if (pre->data == d)
return pre;
pre = pre->next;
}
return NULL;
}
void InsertFront(pNode node, DataType d)
{
assert(node != NULL);
DataType tmpD = node->data;
pNode tmp = node->next;
node->next = BuyNode();
node->data = d;
node->next->data = tmpD;
node->next->next = tmp;
}
void InversionList(pList* plist)
{
if (*plist==NULL)
printf("空链表\n");
if ((*plist)->next == NULL)
return;
pNode pre = (*plist)->next;
pNode cul = pre;
(*plist)->next = NULL;
while (pre!=NULL)
{
cul = cul->next;
pre->next = *plist;
*plist = pre;
pre = cul;
}
}
pNode GetEndNode(pList plist)
{
pNode pre = plist;
while (pre->next!=NULL)
{
pre=pre->next;
}
return pre;
}