单链表的插入(结构体+链表)

单链表的插入(结构体+链表)

题目描述

1.问题描述

单链表初始为空,给定插入位置和数据,插入结点实现单链表的创建。假设单链表中的结点计数从1开始。

2.算法

单链表结点的存储结构包含两部分:数据、下一结点指针

单链表的查找:给出位置i,若第i个结点存在(1<=i<=表中结点数L),返回结点地址;否则,返回NULL。

单链表的插入:给出位置i和数据e,在单链表第i(1<=i<=L+1)个结点位置插入新结点,数据为e。

输入

测试次数n

每行一组测试数据,格式如下:

位置i 数据e

输出

对每组测试数据,调用插入函数在位置i插入数据e,若插入成功,输出当前链表中的数据;若插入不成功,输出error。

示例输入

8
0 10
1 10
2 20
3 30
1 40
6 60
5 50
9 100

示例输出

error
10
10 20
10 20 30
40 10 20 30
error
40 10 20 30 50
error

#include<iostream>
using namespace std;
struct Node
{
	int data;
	Node *next;
};
int insert(Node *head,int index,int val);
void distory(Node *head);
int main()
{
	int n,m;
	cin>>n;
	struct Node *head=new Node;
	head->data=1;
	head->next=NULL;
	for(m=0;m<n;m++)
	{
		int i,e,d,j;
		cin>>i>>e;
		d=insert(head,i,e);
		struct Node *p=head;
		if(d==0)
		cout<<"error"<<endl;
		else
		{
			for(j=1;j<=head->data;j++)
			{
				if(p->next)
				{
					p=p->next;
					cout<<p->data;
					if(j!=head->data-1)
					cout<<" ";
				}
			}
			cout<<endl;
		}
	}
	distory(head);
	return 0;
}

int insert(Node *head,int index,int val)
{
	int i;
	if(index<1||index>=head->data+1)
	  return 0;
	Node *p=new Node;
	p->data=val;
	Node *q=head;
	for(i=1;i<index;i++)
	{
		q=q->next;	
	}
	p->next=q->next;
	q->next=p;
	head->data++;
	return 1;
}

void distory(Node *head)
{
	Node *p;
	while(head->next)
	{
		p=head->next;
		head->next=p->next;
		delete p;
	}
	delete head;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值