微软2014校园招聘笔试编程题

本文介绍了一种不使用额外空间的链表变形算法,通过改变节点的next指针来实现特定的链表结构调整。该方法需要遍历链表n/2次,并提供了完整的C++代码实现与示例。

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

如上题目所示:写代码实现题目要求。 我通过改变结点next 指针位置实现了题目要求,没有用到额外空间,但是需要遍历链表n/2次,各位有什么好的方法欢迎在下面评论,谢谢!。

 

#include <iostream>
using namespace std;
struct node
{
	int elem;
	node* next;
};

void insert(node **rootp,int value)
{
	node *newNode=new node;
	if (newNode==NULL)
	{
		cout<<" memory error \n";
	}
	newNode->elem=value;
	newNode->next=*rootp;
	(*rootp)=newNode;
}

void PrintList(node *root)
{
	if (root==NULL)
	{
		cout<<"empty list \n";
		return ;
	}
	while (root)
	{
		cout<<root->elem<<" ";
		root=root->next;
	}
	cout<<endl;
}
//找到每次需要更改指针的结点,发现一个规律每次需要改变的结点都可以通过从root结点走链表长度减一步得到
node * addressofnode(node *root,int count)
{
	while (count&&root->next)
	{
		root=root->next;
		count--;
	}
	return root;
}

void ModifyList(node *root,int len)
{
	if (root==NULL||root->next==NULL)
	{
		return ;
	}
	node *p=root;
	node *pnext=NULL;
	node *q=NULL;
	pnext=root->next;
	int count=len-1;
	//循环结束条件是当pnext下个结点是寻找到q指针指向的结点,意味着pnext指向了链表尾结点
	while (q!=pnext->next)
	{
		q=addressofnode(root,count);
		p->next=q;
		q->next=pnext;
		p=pnext;
		//如果pnext下一个结点是q意味着pnext不需要往后移动!
		if (q!=pnext->next)
		{
			pnext=pnext->next;
		}		
	}
	pnext->next=NULL;
}

int main()
{
	int a[]={5,6,7,8,10};
	node *LA=NULL;
	for (int i=0;i<5;i++)
	{
		insert(&LA,a[i]);
	}
	PrintList(LA);
	ModifyList(LA,5);
	PrintList(LA);
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值