单链表的基本操作(增删改查)


#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>

#define LEN sizeof(node)
typedef struct Node{
	int data;
	struct Node * next;
}node;//定义结点node

void creat_link(node *head){
	head->next = NULL;
	node *h = (node *)malloc(LEN);
    h = head;
	if (h!=NULL)
	for (int i = 1; i <= 6; i++){
		node * p = (node *)malloc(LEN);
		p->data = i;
		p->next = h->next;
		h->next = p;
		h=p;//尾插法
	}
}

void printf_link(node * head){//打印结点
	node *p = (node *)malloc(LEN);
	p = head->next;
	if (head !=NULL)
	while (p != NULL){
		printf("%-4d", p->data);
		p = p->next;
   }
	putchar('\n');
}
void insert_node(node *head, int n){ //增加一结点 插入位置在第n个结点位置
	node *h = (node *)malloc(LEN);
	node *insert = (node *)malloc(LEN);
	h = head->next;
	
	if (head != NULL){
		for (int i = 1; i < n-1; i++)
			h = h->next;
	}  
	insert->data = 111 ;
	insert->next = h->next;
	h->next = insert;
	
}

void delete_node(node *head, int n){//删除指定位置的结点
	node *h = (node *)malloc(LEN);
	node * p = (node *)malloc(LEN);
	h = head->next;
	if (h != NULL){
		for (int i = 1; i < n-1; i++){
			h = h->next;
		}
		p = h->next;
		h->next = p->next;
		free(p);
	}
}

void  update_node(node *head, int n, int m){//修改某一结点的数据域
	node *h = (node *)malloc(LEN);
	h = head->next;
	if (h != NULL){
		for (int i = 1; i < n; i++)
			h = h->next;
		h->data = m;
	}

}
void search_node(node *head, int m) 
{//查找某一结点
	node *h = (node *)malloc(LEN);
	int  count = 0;
	h = head->next;
	if (head != NULL){
		while (h != NULL){
			count++;
			if (h->data == m)
				break;
			h = h->next;
		}
	}
	if (h == NULL) printf("未找到\n");
	else
		printf("已找到 ,在第%d结点\n", count);
}




int  main(){
	node *head = (node *)malloc(LEN);
	creat_link(head);
	printf_link(head);


	insert_node(head,4);
	printf_link(head);
	delete_node(head, 4);
	printf_link(head);
	
	update_node(head, 4, 111);
	printf_link(head);

	search_node(head, 6);
	return 0;
}

提示:本人在学习链表中,后期会详细讲解单链表内容.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值