C语言之单向链表详解及实例代码
1,单向链简洁。
单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始;链表是使用指针进行构造的列表;又称为结点列表,因为链表是由一个个结点组装起来的;其中每个结点都有指针成员变量指列表中的下一个结点;列表是由结点构成,由head指针指向第一个成为表头的结点而终止于最后一个指向nuLL的指针;
2,例子要求:
根据示例代码中的例子,完成单向链表(singlelinkedlist)中的以字符串为数据的链表的插入、删除以及查找,并支持单向链表的反转;
3,代码实现。
#include<stdio.h>
#include<math.h>
#include<cstring>
#include<memory.h>
#include<malloc.h>
//节点的定义
typedefstructNode{
void*data;//数据域//链域
structNode*next;
}NodeStruct,*pNode;
pNodehead=NULL;
typedefchar(*pCompareFunc)(void*a,void*b);
typedefvoid*(*pChar)(void*p);
//字符串判断
intstr_compare(void*a,void*b){
char*pa=(char*)a;
char*pb=(char*)b;
returnstrcmp(pa,pb);
}
//分配一个节点
pNodeallocate_node(void*data,pCharchar_func){
pNodenode=allocate();
node->data=char_func(data);
returnnode;
}
//创建节点
pNodeallocate(){
void*p=malloc(sizeof(NodeStruct));
pNodenode=(pNode)p;
node->next=NULL;
node->data=NULL;
returnnode;
}
//添加一个节点
voidinsertNode(pNodenode){
if(head==null){
head=node;
}
else{
node->next=head;
head=node;
}
}
void*char_char(void*p){
char*pa=(char*)malloc(sizeof(char));
memcpy(pa,p,sizeof(char));
returnpa;
}
//初始化节点
pNodeallocate_node(void*data,pCharchar_func){
pNodenode=allocate();
node->data=char_func(data);
returnnode;
}
//释放资源
voidfree_list(pNodenode){
pNodenext=node;
while(next!=NULL){
if(next->data!=NULL)
free(next->data);
pNodetemp=next;
next=next->next;
free(temp);
}
}
//1.1添加一个节点
voidinsert(pNodenode){
if(head==NULL)
head=node;
else{
node->next=head;
head=node;
}
}
//1.2查找
intstr_search(void*data,pCompareFunccompare){
pNodenext=head;
pNodeprev=NULL;
while(next!=NULL){
if(compare(data,next->data)==0){
//如果查找到了,就退出返回1
return1;
break;
}
prev=next;
next=next->next;
}
//如果一直查找不到,就返回0
return0;
}
//1.3删除节点
voidremove(void*data,pCompareFunccompare){
pNodenext=head;
pNodeprev=NULL;
while(next!=NULL){
if(compare(data,next->data)==0){
if(prev==NULL){
head=next->next;
next->next=NULL;
free_list(next);
}else{
prev->next=next->next;
next->next=NULL;
free_list(next);
}
break;
}
prev=next;
next=next->next;
}
}
//1.4反转
voidinvert_order()
{
node*This,*prev;
p=head.next;
This=NULL;
while(p){
prev=This;
This=p;
p=p->next;
This->next=prev;
}
head.next=This;
}
voidmain(){
//1单向链表
chara1[]='aaa1';
chara2[]='aaa2';
chara3[]='aaa3';
//1.1添加
insertNode(allocate_node(a1,init_char));
insertNode(allocate_node(a2,init_char));
insertNode(allocate_node(a3,init_char));
//1.2查找
intflag=0;
flag=str_search(&a2,str_compare);
//1.3删除
remove(&a2,str_compare);
//1.4反转
invert_order();
}
以上就是对 C语言单向联表的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!