一、链表
我觉得还是先把链表捋一下
1、链表的创建
//定义一个链表(结构体)
typedef struct node {
int num;
struct node *next;
} ;
创建一个链表
int creat_node(){
struct node *head,*p,*q,*t;
int i,n,a;
scanf("%d",&n);
head = NULL;//头指针初始为空
for(i=1;i<=n;i++){ //循环读入n个数
scanf("%d",&a);
//动态申请一个空间,用来存放一个结点,并用临时指针p指向这个结点
p=(struct node *)malloc(sizeof(struct node));
p->data=a;//将数据存储到当前结点的data域中
p->next=NULL;//设置当前结点的后继指针指向空,也就是当前结点的下一个结点为空
if(head==NULL)
head=p;//如果这是第一个创建的结点,则将头指针指向这个结点
else
q->next=p;//如果不是第一个创建的结点,则将上一个结点的后继指针指向当前结点
q=p;//指针q也指向当前结点
}
return head;
}
2、链表的操作
输出链表内容
void out(struct node *head) {
struct node *t;
t=head;
while(t!=NULL) {
printf("%d ",t->data);
t=t->next;
}
}
修改链表内容
void change_node(struct node *head, int n) {
//n为第n个节点
struct node *t = head;
int i = 0;
while (i < n && t != NULL) {
t = t->next;
i++;
}
if (t != NULL) {
scanf("%d", &t->data);
}
else {
puts("节点不存在");
}
}
删除链表内容(删除第i个)
void delete_node(struct node *head, int n){
struct node *t = head, *in;
int i = 0;
while (i < n && t != NULL) {
in = t;
t = t->next;
i++;
}
if (t != NULL) {
in->next = t->next;
free(t);
}
else {
puts("节点不存在");
}
}
插入链表
void insert_node(struct node *head, int n) {
struct node *t = head, *in;
int i = 0;
while (i < n && t != NULL) {
t = t->next;
i++;
}
if (t != NULL) {
in = (struct node *)malloc(sizeof(struct node *));
scanf("%d", &in->data);
in->next = t->next;//填充in节点的指针域,也就是说把in的指针域指向t的下一个节点
t->next = in;//填充t节点的指针域,把t的指针域重新指向in
}
else {
puts("节点不存在");
}
}