1. 程式人生 > >單向非循環鏈表:鏈表創建、節點插入、鏈表打印、節點長度計算、鏈表清空、鏈表銷毀

單向非循環鏈表:鏈表創建、節點插入、鏈表打印、節點長度計算、鏈表清空、鏈表銷毀

lib pri i++ ins pty ini 打印 node alloc

/* 單向非循環鏈表:
初始化
前插入

後插入
打印
鏈表長度
清空
銷毀
*/
#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\n");
return -1;
}

printf("pNewNode address: %p\n", 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\n");
return -1;
}

printf("pNewNode address: %p\n", 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\n");
return -1;
}

printf("pNewNode address: %p\n", 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\n");
return -1;
}

if (NULL == pN->pNext)
{
printf("printList is NULL\n");
return -1;
}

while(NULL != pN)
{
printf("Node address: %p, Node value: %3d, Node Next: %p\n", pN, pN->data, pN->pNext);
pN = pN->pNext;
}

return 0;
}

/* 鏈表長度 */
int listLength(Node *pN)
{
int len = 0;

if (NULL == pN)
{
printf("listLength NULL\n");
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\n");
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\n", listLength(pHeadNode));
printList(pHeadNode);

emptyList(pHeadNode);
destoryList(&pHeadNode);

printList(pHeadNode);

return 0;
}

單向非循環鏈表:鏈表創建、節點插入、鏈表打印、節點長度計算、鏈表清空、鏈表銷毀