需要实现无头单向链表,实现初始化、插入、删除三个函数接口。
代码:
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node{
struct Node *_pNext;
DataType _data;
}Node, *pNode;
void init_list(pNode *ppHead){
*ppHead = NULL;
}
int insert_list(pNode *ppHead, DataType data){
pNode p = (pNode)malloc(sizeof(Node));
if(p == NULL) return -1;
p->_data = data;
p->_pNext = NULL;
if(*ppHead == NULL){
*ppHead = p;
}else{
p->_pNext = *ppHead;
*ppHead = p;
}
return 0;
}
int remove_list(pNode *ppHead, DataType data){
pNode pre = NULL;
pNode tmp = *ppHead;
if(tmp == NULL) return -1;
do{
if(tmp->_data == data){
if(pre == NULL){
*ppHead = tmp->_pNext;
}else{
pre->_pNext = tmp->_pNext;
}
free(tmp);
return 0;
}
pre = tmp;
tmp = tmp->_pNext;
}while(tmp);
return -2;
}
void print_list(pNode pHead){
pNode tmp = pHead;
if(tmp == NULL) return;
int count = 0;
printf("=======================\n");
do{
printf("%d\t%d\n", count++, tmp->_data);
tmp = tmp->_pNext;
}while(tmp);
printf("-----------------------\n");
}
pNode g_plist;
int main(){
init_list(&g_plist);
DataType d = 123;
insert_list(&g_plist, d);
insert_list(&g_plist, 456);
insert_list(&g_plist, 789);
print_list(g_plist);
remove_list(&g_plist, 456);
print_list(g_plist);
insert_list(&g_plist, 111);
insert_list(&g_plist, 222);
insert_list(&g_plist, 333);
print_list(g_plist);
remove_list(&g_plist, 333);
print_list(g_plist);
remove_list(&g_plist, 123);
print_list(g_plist);
insert_list(&g_plist, 123);
insert_list(&g_plist, 456);
print_list(g_plist);
remove_list(&g_plist, 111);
remove_list(&g_plist, 222);
print_list(g_plist);
return 0;
}
运行结果:
$ ./test
=======================
0 789
1 456
2 123
-----------------------
=======================
0 789
1 123
-----------------------
=======================
0 333
1 222
2 111
3 789
4 123
-----------------------
=======================
0 222
1 111
2 789
3 123
-----------------------
=======================
0 222
1 111
2 789
-----------------------
=======================
0 456
1 123
2 222
3 111
4 789
-----------------------
=======================
0 456
1 123
2 789
-----------------------
本文介绍了一个无头单向链表的数据结构实现,包括初始化、插入和删除操作的具体代码实现。通过C语言,展示了如何创建节点,插入数据到链表头部,以及如何根据数据值从链表中删除节点。
3420

被折叠的 条评论
为什么被折叠?



