单链表--在第i个位置前插入新元素/在第j个位置删除一个元素

实验内容

        建立带头节点的单链表,编写算法,在第i个位置前插入一个新元素,在第j个位置删除一个元素

运行过程:

        手动输入单链表长度并且依次赋值,头节点存放单链表长度

        展示单链表(包括头结点)

        switch case 选择操作

效果图:

完整代码:

#include<stdio.h>
#include <stdlib.h>

struct node {
	int data;      //数据域
	struct node *next; //指针域
};

// 在第i个元素之前插入数据元素e
int ListInsert_N(node *N,int x,int y) {
	struct node *P,*S;
	P = N;
	S=(struct node *)malloc(1*sizeof(struct node));
	int J = 0;
	while (P && J < x - 1 ) {
		P = P->next;
		++J;
	}
	if (!P || J > x ) {
		printf("数据不合法");
		return 0;
	}
	S->data = y;
	S->next = P->next;
	P->next = S;
	P = N->next;
	while(P) {

		printf("%d\t",P->data);
		P=P->next;
	}
	printf("\n");
	return 0;

}

//单链表 删除第i个结点 返回所删除的数据
int ListDelete_N(node *N,int x,int num) {
	if(x>num){
		printf("数据不合法");
		return 0;
	}
	struct node *P,*S;
	P = N;
	S=(struct node *)malloc(1*sizeof(struct node));
	int J = 0;
	while (P&& J < x - 1) {
		P = P->next;
		++J;
	}
	if (!(P->next) || J > x) {
		printf("数据不合法");
		return 0;
	}
	S = P->next;
	P->next = S->next;
	printf("删除元素:%d\n",S->data);
	free(S);
	P = N->next;
	printf("剩余元素:");
	while(P) {

		printf("%d\t",P->data);
		P=P->next;
	}
	return 0;
};

int main() {
	int i,num,x,y;
	char choose;
	struct node *head ,*N;
	//生成一个有头节点链表
	head=(struct node *)malloc(1*sizeof(struct node));
	N=head;
	printf("请输入该链表元素个数:") ;
	scanf("%d",&num);
	N->data=num;
	for(i=0; i<num; i++) {
		N->next = (struct node *)malloc(1*sizeof(struct node));
		N = N->next;
		printf("请为节点%d赋值值:",i+1);
		scanf("%d",&N->data);
	}
	//尾结点next为NULL
	N->next = NULL;
	// 重新设置N的指向;
	N=head;
	printf("生成的单链表为:");
	while(N) {

		printf("%d\t",N->data);
		N=N->next;
	}
	N=head;

	while(1) {
		printf("\n\n\t\t请选择服务种类:");
		printf("\n\n\t\t(A/a):插入元素");
		printf("\n\n\t\t(B/b):删除元素");
		printf("\n\n\t\t(C/c):退出\n");
		scanf("\t\t\t%s", &choose);
		switch (choose) {
			case'A':
			case'a': {
				printf("\n在x位置插入数据y:");
				scanf("%d,%d",&x,&y);
				ListInsert_N(N,x,y);
				break;
			}
			case'B':
			case'b': {
				printf("\n在x位置删除数据:");
				scanf("%d,%d",&x);
				ListDelete_N(N,x,num);
				break;
			}
			case'C':
			case'c': {
				return 0;
				break;
			}
			default :
				printf("输入不合法");
				break;

		}
	}

	return 0;
}

初学数据结构,写的不好,对指针的使用也不是特别熟练,望见谅

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

find1star

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

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

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

打赏作者

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

抵扣说明:

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

余额充值