C語言實現(xiàn)帶頭結(jié)點的鏈表的創(chuàng)建、查找、插入、刪除操作
更新時間:2014年09月15日 14:47:17 投稿:shichen2014
這篇文章主要介紹了C語言實現(xiàn)帶頭結(jié)點的鏈表的創(chuàng)建、查找、插入、刪除操作方法,對于了解數(shù)據(jù)結(jié)構(gòu)中鏈表的各項操作有很好的借鑒價值,需要的朋友可以參考下
本文實例講述了C語言實現(xiàn)帶頭結(jié)點的鏈表的創(chuàng)建、查找、插入、刪除操作。是數(shù)據(jù)結(jié)構(gòu)中鏈表部分的基礎(chǔ)操作。分享給大家供大家參考。具體方法如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* next;// 這個地方注意結(jié)構(gòu)體變量的定義規(guī)則
} Node, *PNode;
Node* createLinklist(int length)
{
int i = 0;
PNode pHeader = NULL;
PNode pTail = NULL;
PNode pTemp = NULL;
printf("create\n");
pHeader = (PNode)malloc(sizeof(Node));// 申請頭結(jié)點
if (!pHeader)
{
exit(-1);
}
pHeader->next = NULL;
for (i = 0; i < length; i++)
{
pTemp = (PNode)malloc(sizeof(Node));// 用malloc要包含頭文件
if (!pTemp)
{
exit(-1);
}
pTemp->data = i*10;
pTemp->next = NULL;
if (!pHeader->next)
{
// 第一個結(jié)點是空的,則先連接第一個結(jié)點
pHeader->next = pTemp;
}
else
{
pTail->next = pTemp;
}
pTail = pTemp;
}
return pHeader;
}
Node* search(PNode pHeader, int k)
{
PNode p = pHeader->next;
int i = 1;
printf("search\n");
while(p && (i < k))
{
p = p->next;
i++;
}
if (p && (i == k)) // 這步的i == k是必須的,
// 因為如果一開始的時候 i就 >= k并且pHeader->next還不為NULL這一步就會必過,導(dǎo)致返回的是第一個元素的值
{
return p;
}
return NULL;
}
int insert(PNode pHeader, PNode pNew, int k)
{
PNode p = NULL;
printf("insert\n");
if ( 1 == k )
{
p = pHeader;
}
else
{
printf("==>");
p = search(pHeader, k-1);
}
if (p)
{
// 帶頭結(jié)點和不帶頭結(jié)點的主要區(qū)別之一就在這
// 如果不帶頭結(jié)點,那么在第一個位置插入結(jié)點的操作應(yīng)該是
// pNew->next = p;
// p = pNew;
// 帶頭結(jié)點的操作如下
pNew->next = p->next;
p->next = pNew;
return 1;
}
return 0;
}
int deleteNode(PNode pHeader, int k)
{
PNode p = NULL;
printf("deleteNode\n");
if (1 == k)
{
p = pHeader->next;
}
else
{
printf("==>");
p = search(pHeader, k-1);
}
if (p && p->next)
{
// 不帶頭結(jié)點的操作時刪除第一個結(jié)點的操作
// Node* temp = p;
// p = p->next;
// free(temp);
// 帶頭結(jié)點的操作如下
PNode temp = p->next;
p->next = temp->next;
free(temp);
return 1;
}
else
{
printf("Not Found\n");
return 0;
}
}
void print(PNode pHeader)
{
PNode p = pHeader->next;
printf("print\n ");
while(p)
{
printf("%4d ", p->data);
p = p->next;
}
putchar('\n');
}
void freeList(PNode pH)
{
PNode p = NULL;
printf("freeList\n");
while(NULL != pH)
{
p = pH;
pH = pH->next;
printf("%4d be freed\n", p->data);
free(p);
}
}
int main(void)
{
PNode pHeader = NULL;// C和C++中判斷指針為空都是用NULL宏(全大寫)
PNode pNew = NULL;
PNode result = NULL;
pHeader = createLinklist(10);
print(pHeader);
result = search(pHeader, 5);
if ( result )
{
printf("%d\n", result->data);
}
else
{
printf("Not Found\n");
}
pNew = (PNode)malloc(sizeof(Node));
if (!pNew)
{
exit(-1);
}
pNew->data = 100;
pNew->next = NULL;
insert(pHeader, pNew, 5);
print(pHeader);
deleteNode(pHeader, 12);
print(pHeader);
freeList(pHeader);
return 0;
}
上述實例備有較為詳盡的注釋,相信不難理解。希望本文所述對大家C程序數(shù)據(jù)結(jié)構(gòu)與算法設(shè)計有所幫助。

