链表的原理比较容易理解,但很多教材上都是伪代码,导致写出第一个完整可运行代码花了不少时间(自己太蠢,代码量太少了),现在把我写的代码贴出来分享。
这个代码不是非常完善,仅供初学者或者看了伪代码,明白了原理,但写不出完整代码的同学参考。如有错误的地方,烦请大神指出,一定改正。
代码如下:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
//此数组为加入链表的待用数值
int str[5]={1,2,3,4,5};
//初始化链表,使头结点的next为NULL
struct node* list_init(void) {
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->next = NULL;
return temp;
}
//从链表后面加入一个新结点
void list_add(struct node *L,struct node *new) {
struct node *temp = L;
while (temp->next != NULL) {
temp = temp-> next;
}
temp->next = new;
}
//将数组的元素放在链表中来
void list_create(struct node *L) {
struct node *temp;
int i;
for(i=0;i<5;i++) {
temp = (struct node*)malloc(sizeof(struct node));
temp->data=str[i];
temp->next=NULL;
list_add(L,temp);
}
}
//判断链表是否为空,即头点的next是否为NULL
int list_isempty(struct node *L) {
return L->next == NULL;
}
//判断某个结点是否为尾结点
int list_islast(struct node *p,struct node *L) {
return p->next ==NULL;
}
//找到第一个元素值为x的结点的前驱
struct node* list_find(int x,struct node *L) {
struct node *temp = L;
while (temp->next !=NULL && temp->next->data != x) {
temp = temp ->next;
}
return temp;
};
//删除某个元素值为x的结点
void list_delete(int x,struct node *L) {
struct node *temp,*p;
p = list_find(x,L);
temp = p->next;
p->next = temp->next;
free(temp);
}
//输出链表
void list_dump(struct node *L)
{
struct node *p = L->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//插入值为x的结点,p为插入成功后 元素值为x的结点 的前驱
void list_insert(int x,struct node *p,struct node *L) {
struct node *new;
new = (struct node *)malloc(sizeof(struct node));
new->data = x;
new->next = p->next;
p->next = new;
}
//删除整个链表(头结点依然保存,相当于清空数据结点)
void list_deletelist(struct node *L) {
struct node *temp,*p;
p = L ->next;
L->next = NULL;
while(p) {
temp = p->next;
free(p);
p = temp;
}
}
int main()
{
struct node *L,*temp;
L=list_init();
list_create(L);
printf("初始化创建链表结果:\n");
list_dump(L);
list_delete(3,L);
printf("删除第一个元素值为3的结点:\n");
list_dump(L);
temp = list_find(4,L);
list_insert(3,temp,L);
printf("数值4前面插入数值3:\n");
list_dump(L);
list_deletelist(L);
printf("删除整个链表后的结果:\n");
list_dump(L);
return 0;
}
运行结果如下: