单向非循环链表:链表创建节点插入链表打印节点长度计算链表清空链表销毁
Posted tedani
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单向非循环链表:链表创建节点插入链表打印节点长度计算链表清空链表销毁相关的知识,希望对你有一定的参考价值。
/* 单向非循环链表:
初始化
前插入
后插入
打印
链表长度
清空
销毁
*/
#include <stdio.h>
#include <stdlib.h>
#define itemType int
typedef struct node
{
itemType data;
struct node *pNext;
}Node;
/* 创建Head节点: 节点的pNext为NULL */
int initList(Node **ppN)
{
Node *pNewNode = (Node *)malloc(sizeof(Node));
if (NULL == pNewNode)
{
printf("initList fail
");
return -1;
}
printf("pNewNode address: %p
", pNewNode);
pNewNode->pNext = NULL;
pNewNode->data = 0;
*ppN = pNewNode;
return 0;
}
/* 前向插入一个节点 */
int insertListHead(Node *pN, itemType data)
{
Node *pNewNode = (Node *)malloc(sizeof(Node));
if (NULL == pNewNode)
{
printf("insertListHead fail
");
return -1;
}
printf("pNewNode address: %p
", pNewNode);
pNewNode->pNext = NULL;
pNewNode->data = data;
pNewNode->pNext = pN->pNext;
pN->pNext = pNewNode;
return 0;
}
/* 后向插入一个节点 */
int insertListTail(Node *pN, itemType data)
{
Node *pNewNode = (Node *)malloc(sizeof(Node));
if (NULL == pNewNode)
{
printf("insertListTail fail
");
return -1;
}
printf("pNewNode address: %p
", pNewNode);
pNewNode->pNext = NULL;
pNewNode->data = data;
/* 查找最后一个节点 */
while(NULL != pN->pNext)
{
pN = pN->pNext;
}
pN->pNext = pNewNode;
return 0;
}
/* 链表打印 */
int printList(Node *pN)
{
if (NULL == pN)
{
printf("printList is not exist
");
return -1;
}
if (NULL == pN->pNext)
{
printf("printList is NULL
");
return -1;
}
while(NULL != pN)
{
printf("Node address: %p, Node value: %3d, Node Next: %p
", pN, pN->data, pN->pNext);
pN = pN->pNext;
}
return 0;
}
/* 链表长度 */
int listLength(Node *pN)
{
int len = 0;
if (NULL == pN)
{
printf("listLength NULL
");
return 0;
}
while(NULL != pN->pNext)
{
len++;
pN = pN->pNext;
}
return len;
}
/* 清空链表:保留Head节点,其它全部资源 释放 */
int emptyList(Node *pN)
{
Node *pTempNode = NULL;
if (NULL == pN)
{
printf("emptyList is NULL
");
return -1;
}
while (NULL != pN->pNext)
{
pTempNode = pN->pNext;
pN->pNext = pTempNode->pNext;
free(pTempNode);
}
pTempNode = NULL;
return 0;
}
/* 销毁链表:释放所有节点,包括Head节点 */
int destoryList(Node **pN)
{
emptyList(*pN);
free(*pN);
*pN = NULL;
return 0;
}
/* 测试入口 */
int main(void)
{
Node *pHeadNode = NULL;
initList(&pHeadNode);
for (int i=0; i<20; i++)
{
insertListHead(pHeadNode, i+1);
insertListTail(pHeadNode, i+101);
}
printf("listLength: %d
", listLength(pHeadNode));
printList(pHeadNode);
emptyList(pHeadNode);
destoryList(&pHeadNode);
printList(pHeadNode);
return 0;
}
以上是关于单向非循环链表:链表创建节点插入链表打印节点长度计算链表清空链表销毁的主要内容,如果未能解决你的问题,请参考以下文章