# 简单单链表的实现—C语言

- 单链表的创建
- 单链表的查找
- 单链表的删除
- 单链表的打印
- 单链表的清除

## 实现代码

### node.h

#ifndef _NODE_H_
#define _NODE_H_

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

#endif

### main.c

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

#include "node.h"

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

typedef struct _list{
} List;

void list_add(List* pList, int number);
void list_find(List* pList, int number);
void list_delete(List* pList, int number);
void list_print(List* pList);
void list_clear(List* pList);

int main(){

List list;

printf("Please input some number of int: ");
int number = 0;
do{
scanf("%d", &number);
if (number != -1){
}
} while (number != -1);

printf(" this is list your input: ");
list_print(&list);
printf("\n");

printf("Please input one number of int,it will add that list: ");
int s = 0;
scanf("%d", &s);

printf(" this is list your input: ");
list_print(&list);
printf("\n");

printf("Please input one number of int,we will find it at your list: ");
int n = 0;
scanf("%d", &n);
list_find(&list, n);

printf("Please input one number of int,we will delete it at your list: ");
int m = 0;
scanf("%d", &m);
list_delete(&list, m);

printf(" this is list your input: ");
list_print(&list);
printf("\n");

list_clear(&list);

printf(" this is list is cleared! ");

return 0;
}

void list_add(List* pList, int number){
// add to liked-list
Node* p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;

Node* last = pList->head;
if (last){
// find last
while (last->next){
last = last->next;
}
//attach
last->next = p;
}
else{
}
}

void list_print(List* pList){
Node* p;
for (p = pList->head; p; p = p->next){
printf("%d\t", p->value);
}
}

void list_delete(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 list_find(List* pList, int n){
int isFind = 0;
Node* p;
for (p = pList->head; p; p = p->next){
if (p->value == n){
printf("Find!\n");
isFind = 1;
break;
}
}
if (!isFind){
printf("Not Find!\n");
}
}

void list_clear(List* pList){
Node *p,
*q;
for (p = pList->head; p; p = q){
q = p->next;
free(p);
}
}

## 调试

1、单链表创建完成后如下图，大家可以想想内存上的情况：

2、充分理解for(;;){}

• 第一次运行到main.c的127行

• 第二次运行到main.c的127行

• 本文已收录于以下专栏：

举报原因： 您举报文章：简单单链表的实现—C语言 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)