【数据结构_链表_List_0953】单链表的删除操作实现

本文介绍了一种在单链表中删除指定位置前一个节点的算法实现,通过C++代码展示了如何创建单链表,并在合法条件下删除指定位置前的节点,最后输出删除后的链表元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立长度为n的单链表,删除第i个结点之前的结点。

第一行为自然数n,表示链式线性表的长度; 
第二行为n个自然数表示链式线性表各元素值; 
第三行为指定的删除参数i。 

指定删除位置合法时候,输出删除元素后的链式线性表的所有元素,元素之间用一个空格隔开。 
输入不合法,输出"error!".

-----------------------------------------

5

1 2 3 4 5

3

________________________

1 3 4 5




#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node
{
	int data;
	struct node *next;
};
int main()
{
	int length,tar;
	struct node *head,*p,*q,*temp,*t;
	while(cin>>length)
	{
		head=(struct node *)malloc(sizeof(struct node));
		int i,j;
		p=head;
		for(i=0;i<length;i++)
		{
			q=(struct node *)malloc(sizeof(struct node));
			cin>>q->data;
			p->next=q;
			p=q;
		}
		p->next=NULL;
		cin>>tar;
		temp=head;
		if(tar<=1 || tar>length)
		{
			cout<<"error!";
			break;
		}
		else
		{
			t=(struct node *)malloc(sizeof(struct node));
			for(j=0;j<tar-1;j++)
			{
				t=temp;
				temp=temp->next;
			}
			t->next=temp->next;
			length--;
		}
		temp=head;
		temp=temp->next;
		while(temp!=NULL)
		{
			cout<<temp->data<<" ";
			temp=temp->next;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值