C语言——单链表相关操作(以函数形式呈现)

这篇博客是对之前单链表相关操作的一个改进,上篇博客只能对链表进行相关操作,但并不是最优的方式,但是思想与前篇博客中各个操作的思想都是一样的,只不过在变量名的定义上会有所出入。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

๑Aurora.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值