链表的插入与删除

                                          链表的插入与删除

<span style="font-size:18px;color:#ff0000;">思路:</span>
<span style="font-size:18px;color:#ff0000;">      上学期自学了指针,不知道是没理解透彻,还是其它原因。但是过了两个月后,感觉写起来好像切菜一样,感觉容易了很多。就像大话数据结构里的作者说的,学会了就是这点儿事。</span>
#include <iostream>
using namespace std;
struct S
{
	int a;
	S *next;
}*p,*head,*q;
int i;
void NewRoom(int n)//申请动态空间
{
	head = new S;
	head->next = NULL;//head=NULL会错,我认为是head复制了NULL的地址给自己所以错了
	p=head;
	for (i=0;i<n;++i)
	{
		q = new S;
		cin >> q->a;
		head->next = q;
		head = q;
	}
	head->next=NULL;
}
void insert(int k,int t)//插入元素
{
	head = p;
	while (k--)
	{
		head=head->next;
	}
	q = new S ;
	q->a = t;
	q->next = head->next;
	head->next = q;
}
void Delete(int k)//删除元素
{
	head = p;
	while (k--)
	{
		q=head;
		head = head->next;
	}
	q->next = head->next;
}
void Cout()//输出
{
	p=p->next;
	while (p)
	{
		head=p;
		cout << p->a << " " ;
		p=p->next;
		delete head;
	}
	cout << endl;
}
int main()
{
	int k,n,t;
	while (cin >> n)
	{
		NewRoom(n);
		cin >> k >> t;//插入一个数,k为位置,t为数值
		insert(k,t);
		/*cin >> k;
		Delete(k);*/
		Cout();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值