在无头单链表的一个节点前插入一个节点(不能遍历链表) (C++)详细

算法思想
在这里插入图片描述


代码
#include<iostream>
using namespace std;

struct list
{
	int val;
	list* next;
	list(int x):val(x),next(nullptr){}
};


list* insert(list* head,int x) {
	list* p = head;
	while (p->next)
	{
		p = p->next;
	}
	list* t = new list(x);
	p->next = t;
	return head;
}

void pprint(list* head) {
	if (nullptr == head) {
		cout << "链表为空;";
		return;
	}
	while(nullptr != head->next) {
		cout << head->val << "->";
		head = head->next;
	}
		cout << head->val << endl;
	}

//在无头单链表的一个节点前插入一个节点(不能遍历链表)
void ffrontinsert(list* target,list* t) {
	list* temp = target->next;
	swap(t->val, target->val);
	t->next = temp;
	target->next = t;
}

//找打最后一个节点
list* last(list* head) {
	list* p = head;
	while (p->next)
	{
		p = p -> next;
	}
	return p;
}

int main() {
	list* head = new list(0);
	for (int i = 1; i < 5; i++) {
		insert(head, i);
	}
	
	list* p = last(head);


	cout << "初始链表:  ";
	pprint(head);
	cout << "在最后一个节点之前插入-1:  ";
	list* t = new list(-1);
	ffrontinsert(p, t);
	pprint(head);
	cout << "在第一个节点之前插入-1:  ";
	list* a = new list(-1);
	ffrontinsert(head, a);
	pprint(head);
	return 0;
}
运行结果

在这里插入图片描述

在写测试main的时候,注意我这里new了一个t和a,由于我的大意,将t插入最后一个节点后,又将t插入第一个节点之前,这就会使得运行的时候出现死循环的情况。才恍然大悟我的t都已经插入到链表了,我怎么还能再次插入呢?所以一定不要疏忽需要创建新的节点进行插入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值