欢迎浏览我的博客
这里推荐一下 网易云课堂北京图灵学院,我正在学习数据结构,那里开设了一个数据结构的课程,不过演示的是python代码,我这里给出C代码,目前来看是正确的,但不确定,仅供参考
下面直接放代码
#include<stdio.h>
typedef struct SingleNode
{
int item;
struct SingleNode *next;
}SingleNode;
//初始化链表
SingleNode init();
//链表判空
_Bool isEmpty(SingleNode list);
//链表求长
int length(SingleNode list);
//遍历链表
void travel(SingleNode list);
//插入头结点
void addFirst(SingleNode *list,int item);
//插入尾结点
void append(SingleNode *list,int item);
//插入任意位置结点
void insert(SingleNode *list,int pos,int item);
//删除结点
void re(SingleNode *list,int item);
//查看结点是否存在
_Bool search(SingleNode list,int item);
int main()
{
SingleNode list = init();
addFirst(&list,10);
addFirst(&list,20);
append(&list,30);
insert(&list,2,4);
printf("list的长度为%d\n",length(list));
printf("遍历list:\n");
travel(list);
printf(search(list,30)?"30在list中\n":"30不再list中\n");
printf(search(list,32)?"32在list中\n":"32不再list中\n");
printf("删除20\n");
re(&list,20);
printf("list的长度为%d\n",length(list));
printf("遍历list:\n");
travel(list);
return 0;
}
SingleNode init()
{
SingleNode new; //头结点
new.item = 0; //头结点保存链表长度
new.next = NULL;
return new;
}
_Bool isEmpty(SingleNode list)
{
return list.next == NULL ;
}
int length(SingleNode list)
{
return list.item;
}
void travel(SingleNode list)
{
SingleNode cur = list;
while(cur.next!=NULL)
{
cur = *(cur.next);
printf("%d\n",cur.item);
}
}
void addFirst(SingleNode *list,int item)
{
SingleNode *new = (SingleNode *)malloc(sizeof(SingleNode));
new->item = item;
new->next = list->next;
list->next = new;
++(list->item);
}
void append(SingleNode *list,int item)
{
SingleNode *new = (SingleNode *)malloc(sizeof(SingleNode));
SingleNode *cur = list;
while(cur->next!=NULL)
{
cur = cur->next;
}
new->item = item;
new->next = NULL;
cur->next = new;
++(list->item);
}
void insert(SingleNode *list,int pos,int item)
{
int i;
SingleNode *cur = list;
if(pos<=0)
{
addFirst(list,item);
}
else if(pos>=list->item)
{
append(list,item);
}
else
{
for(i=0;i<pos;++i)
{
cur = cur->next;
}
SingleNode *new = (SingleNode *)malloc(sizeof(SingleNode));
new->item = item;
new->next = cur->next;
cur->next = new;
++(list->item);
}
}
void re(SingleNode *list,int item)
{
SingleNode *cur = list->next; //当前结点
SingleNode *pre = list; //当前结点的上一个结点
while(cur!=NULL)
{
if(cur->item == item)
{
pre->next = cur->next;
free(cur); //删除结点后,要释放内存,防止内存泄漏
cur = NULL;
--list->item;
}
else
{
pre = cur;
cur = cur->next;
}
}
}
_Bool search(SingleNode list,int item)
{
SingleNode *cur = list.next;
while(cur!=NULL)
{
if(cur->item == item)
{
return 1;
}
else
{
cur = cur->next;
}
}
return 0;
}