#ifndef LINKLIST_H
#define LINKLIST_H
struct Student {
int num;
struct Student* pnext;
};
struct Student* initlink();
int pianli(struct Student* x);
void charu(struct Student* x, int num);
void shanchu(struct Student* x, int num);
#endif
#include <stdio.h>
#include <stdlib.h>
#include"linklist.h"
#include"linklist.h"
struct Student* initlink() {
struct Student* head = NULL;
struct Student* tail = NULL;
struct Student* new = NULL;
int i;
head = (struct Student*)malloc(sizeof(struct Student));
head->num = 0;
tail = head;
for (i = 0; i < 5; i++) {
new = (struct Student*)malloc(sizeof(struct Student));
new->num = i + 1;
tail->pnext = new;
tail = new;
}
return head;
}
int pianli(struct Student* x) {
struct Student* p = NULL;
for (p = x; p != NULL; p = p->pnext) {
printf("%d ", p->num);
}
}
void charu(struct Student* x, int num) {
struct Student* p = NULL;
struct Student* new = NULL;
new = (struct Student*)malloc(sizeof(struct Student));
new->num = 66;
for (p = x; p != NULL; p = p->pnext) {
if (num == p->num) {
new->pnext = p->pnext;
p->pnext = new;
break;
}
}
}
void shanchu(struct Student* x, int num) {
struct Student* p = NULL;
struct Student* tmp = NULL;
for (p = x; p != NULL; p = p->pnext) {
if (p->pnext->num == num) {
tmp = p->pnext;
p->pnext = tmp->pnext;
free(tmp);
break;
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include"linklist.h"
#include"linklist.h"
int main() {
struct Student* head = NULL;
head = initlink();
pianli(head);
charu(head, 3);
printf("\n");
pianli(head);
shanchu(head, 3);
printf("\n");
pianli(head);
return 0;
}
运行结果:
链表创建思路:定义3个结构体指针变量head,tail,new,先malloc一块区域,让head指向这块区域,head给head赋值,然后使tail也指向这块区域。接着进入循环:malloc一块区域,让new指向这块区域,接着给new赋值,让tail->pnext=new,接着让tail也指向这块区域,以此循环,直到tail->pnext=NULL。
链表遍历思路:定义一个结构体指针变量p,让p先指向head,然后指向pnext,然后不断指向下一个pnext,直到pnext=NULL。
链表插入思路:1.定义一个结构体指针变量new
2.new->pnext=p->pnext;
3.p->pnext=new。
链表删除思路:1.定义一个结构体指针变量tmp;
2.p->pnext=tmp->pnext;
free(tmp)。