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

178人阅读 评论(0)

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

## 实现代码

### 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_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");

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;
}

Node* p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;

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行

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：13550次
• 积分：468
• 等级：
• 排名：千里之外
• 原创：26篇
• 转载：14篇
• 译文：0篇
• 评论：0条