这篇博客是对之前单链表相关操作的一个改进,上篇博客只能对链表进行相关操作,但并不是最优的方式,但是思想与前篇博客中各个操作的思想都是一样的,只不过在变量名的定义上会有所出入。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}*linklist;
//初始化链表
linklist node(){
linklist head = (linklist)malloc(sizeof(linklist));
head->next = NULL;
return head;
}
//尾插法创建链表
void creatwei(linklist head){
linklist p, q;
p = head;
int n;
printf ("链表长度为:\n");
scanf ("%d",&n);
printf ("输入链表中元素:\n");
while (n>0){
q = (linklist)malloc(sizeof(linklist));
scanf ("%d",&q->data );
q->next = NULL ;
p->next = q;
p = q;
n--;
}
}
//查找
linklist find (linklist head,int position) {
linklist s = head;
position--;
while (position!=0){
s = s->next ;
position--;
}
return s;
}
//插入
void add(linklist head){
int position, n;
printf ("需要插入的位置为:\n");
scanf ("%d",&position);
printf ("想要插入的数字为:\n");
scanf ("%d",&n);
linklist pre = find (head,position);
linklist p = (linklist)malloc(sizeof(linklist));
p->data = n;
p->next = pre->next ;
pre->next = p;
}
//删除
void shanchu(linklist head){
linklist t, s;
int n;
printf ("需要删除的数字位置:\n");
scanf ("%d",&n);
t = find (head,n );
s = t->next ;
t->next = s->next ;
free (s);
}
//改数
void change(linklist head){
int position, n;
linklist t, s;
printf ("需要修改的数字位置:\n");
scanf ("%d",&position);
printf ("想要修改为的数字:\n");
scanf ("%d",&n);
t = find (head,position);
s = t->next ;
s->data = n;
}
//打印链表
void output( linklist head ){
linklist p;
p = head->next;
while(p){
printf("%-3d", p -> data);
p = p -> next;
}
}
//反转链表
void fanzhuan (linklist head){
linklist p1, p2;
p1 = NULL;
p2 = head->next ;
while(p2){
linklist p3;
p3 = p2->next ;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next = p1;
}
int main (void){
printf ("创建链表\n");
linklist head = node();
creatwei(head);
printf ("\n打印链表\n");
output(head);
printf ("\n删除结点\n");
shanchu (head);
output(head);
printf ("\n改数\n");
change(head);
output(head);
printf ("\n插入数据\n");
add (head);
output (head);
printf ("\n反转链表\n");
fanzhuan(head);
output (head);
return 0;
}