删除单链表的第i个结点

#include <stdio.h>

int nodeNum = 5;

struct node
{
	int t;
	node * link;
};

//建表 
struct node *creatlist()
{
	int i = 0;
	int t;
	struct node *head, *p, *q;
	//头结点
	scanf_s("%d", &t);
	head = new struct node;
	head->t = t;
	head->link = 0;
	q = head;

	for (i = 0; i < nodeNum - 1; i++) {
		scanf_s("%d", &t);
		p = new struct node;
		p->t = t;
		p->link = 0;
		q->link = p;
		q = q->link;
	}
	return head;
}

//删除
struct node *deleteOne(struct node *head, int i)
{
	if (head == 0) {
		printf("这是个空表\n");
		return head;
	}
	else if (i<0 || i>nodeNum) {
		printf("指定元素不存在\n");
		return head;
	}
	//可以删除
	struct node *q;
	if (i == 0) {
		q = head;
		head = head->link;
	}
	else{
		struct node *p;
		p = head;
		for (int j = 0; j < i - 1; j++) {
			p = p->link;
		}
		q = p->link;
		p->link = q->link;
	}
	delete q;
	return head;
}

//打印
void print(struct node *head)
{
	struct node *tmp;

	tmp = head;

	while (tmp != NULL)
	{
		printf("%d ", tmp->t);
		tmp = tmp->link;
	}
	printf("\n");
}

//释放
void removeAll(struct node *head)
{
	struct node*p = head;
	while (head) {
		p = head;
		head = head->link;
		delete p;
	}
}

int main()
{
	int i;
	struct node *head = NULL;
	struct node *h = NULL;
	//创建单链表
	printf("输入5个值\n");
	head = creatlist();

	//删除
	printf("删除第几个元素\n");
	scanf_s("%d", &i);
	i = i - 1;
	head = deleteOne(head, i);
	//head = deleteOne(h, i);//空链表

	//打印单链表
	printf("删除后的链表为:\n");
	print(head);

	//释放
	removeAll(head);

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值