单链表插入或删除元素

在单链表按大小顺序插入或删除元素

在这里插入图片描述

//按元素大小顺序插入到链表中
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Node
{
	int value;
	struct Node *next;
};

void insertNode(struct Node **head,int value)
{
	struct Node *previous;
	struct Node *current;
	struct Node *new;

	current = *head;
	previous = NULL;
	
	while(current!=NULL&&current->value < value)
	{
		previous = current;		//previous记录current上一个节点的位置
		current = current ->next;
	}
	new = (struct Node *)malloc(sizeof(struct Node));
	if(new == NULL)
	{
		printf("内存分配失败!");
		exit(1);
	}
	new ->value = value;
	new ->next = current;
	if(previous == NULL)
	{
		*head = new;
	}
	else
	{
		previous ->next = new;
	}
}

void printNode(struct Node *head)
{
	struct Node *current;
	current = head;
	while(current != NULL)
	{
		printf("%d ",current->value);
		current = current ->next;
	}
	printf("\n");
}

void deleteNode(struct Node **head,int value)
{
	struct Node *previous;
	struct Node *current;

	current = *head;
	previous = NULL;

	while(current != NULL && current->value != value)
	{
		previous = current;
		current = current->next;
	}
	if(current == NULL)
	{
		printf("找不到匹配的节点\n");
		return;
	}
	else
	{
		if(previous == NULL)
		{
			*head = current ->next;
		}
		else
		{
			previous ->next = current->next;
		}
		free(current);
	}
}
int main(void)
{
	struct Node *head = NULL;
	int input;
	printf("开始测试插入整数...\n");
	while(1)
	{
		printf("\n请输入一个整数(-1表示结束):");
		scanf("%d",&input);
		printf("\n"); 
		if(input == -1)
		{
			break;
		}
		insertNode(&head,input);
		printNode(head);
	}

		printf("开始测试删除整数...\n");
		while(1)
		{
			printf("\n请输入一个整数(-1表示结束):");
			scanf("%d",&input);
			printf("\n"); 
			if(input == -1)
			{
				break;
			}
			deleteNode(&head,input);
			printNode(head);
		}

	return 0;
}

演示结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值