C语言实现数据结构：零点五.单向链表（热身篇）

构造单向链表

typedef struct _node{
int value;
struct _node *next;
} Node;


typedef struct _list {
} List;


实现单向链表

#include <stdio.h>
#include <stdlib.h>

typedef struct _node{
int value;
struct _node *next;
} Node;

typedef struct _list {
} List;

void add(List *pList, int number)//添加
{
Node *p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
// find the last
Node *last = pList->head;
if(last)
{
while(last->next)
last = last->next;
// attach
last->next = p;
}
else
}

void print(List *pList)//打印链表所有元素
{
Node *p;
for (p=pList->head; p; p=p->next)
printf("%d\t", p->value);
printf("\n");
}

int found(List *pList, int number)//查询元素是否在链表内
{
Node *p;
int isFound = 0;
{
if(p->value == number)
{
printf("is found\n");
isFound = 1;
break;
}
}
if(!isFound)
{
printf("NO found\n");
return 0;
}
else
return 1;
}

void Remove(List *pList, int number)//删除元素
{
Node *p, *q;
for(q=NULL, p=pList->head; p; q=p, p=p->next)
{
if(p->value == number)
{
if(q)
q->next = p->next;
else
free(p);
break;
}
}
}

void empty(List *pList)//清空链表
{
Node *p, *q;
for (p=pList->head; p; p=q)
{
q = p->next;
free(p);
}
}

int main(int argc, char const *argv[])
{
List list;
int number;

//向链表中添加元素，直到输入-1结束
do {
scanf("%d",&number);
if(number != -1)
} while(number != -1);

print(&list);

//输入一个数，查询这个数是否在链表中，是则删除这个数。 直到输入-1结束
while(1)
{
scanf("%d", &number);
if(number != -1)
{
if(found(&list, number))
Remove(&list, number);
print(&list);
}
else	break;
}

empty(&list);

//验证链表是否被清空
printf("list was emptied!\n");

return 0;
}

10-30 4万+
06-23 3582

09-20 2万+
09-06 1431
08-28 1388
09-28 1157
04-15 4302
11-07 5926
04-26 92
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客