C++常见笔试编程题

1从尾到头打印单链表

//栈的方式
void printListReversingly_iteratively(LinkNode* pHead)
{
	std::stack<LinkNode*> nodes;
	LinkNode* pNode = pHead;
	while (pHead!=nullptr) 
	{
		nodes.push(pNode);
		pNode = pNode->m_pNext;
	}
	while (!nodes.empty())
	{
		pNode = nodes.top();
		std::cout << pNode->m_value << " ";
		nodes.pop();
	}
}
//递归
void printListReversingly_recursively(LinkNode* pHead)
{
	if (pHead != nullptr)
	{
		if (pHead->m_pNext != nullptr)
		{
			printListReversingly_recursively(pHead->m_pNext);
		}
		std::cout << pHead->m_value << " ";
	}
}

2反转单链表

Node* ReverseList(Node* pHead)
{
	Node* pReverse = NULL;
	Node* pNode = pHead;
	Node* pPrev = NULL;
	while (pNode!=NULL)
	{
		Node* pNext = pNode->next;
		if (pNext == NULL)
			pReverse = pNode;
		pNode->next = pPrev; 
		pPrev = pNode;
		pNode = pNext;
	}
	return pReverse;
}
Node* ReverseList2(Node* pHead)
{
	if (pHead ==NULL || pHead->next == NULL )
		return pHead;
	Node* pre = pHead;
	Node* cur = pHead->next;
	pre->next = NULL;
	while (cur != NULL)
	{
		Node* next = cur->next;
		cur->next = pre;
		pre = cur;
		cur = next;
	}
	return pre;
}
Node* ReverseList3(Node* pHead)
{
	if (pHead == NULL || pHead->next == NULL)
		return pHead;//递归条件终止,找到链表的最后一个结点
	Node* newHead = ReverseList3(pHead->next);//先递后归,从后往前变量每个节点进行反转
	pHead->next->next = pHead;//将当前结点的后一个结点的next指向当前结点
	pHead->next = NULL;//断开当前结点指向后一个结点
	return newHead;
}
Node* ReverseList4(Node* pHead)
{
	if (pHead == NULL || pHead->next == NULL)
		return pHead;
	Node* newHead = NULL;
	while (pHead != NULL)
	{
		//对之前的链表头删
		Node* node = pHead;
		pHead = pHead->next;
		//对新链表做头插
		node->next = newHead;
		newHead = node;
	}
	return newHead;
}
Node* ReverseList5(Node* pHead)
{
	if (pHead == NULL || pHead->next == NULL)
		return pHead;
	Node* p0 = NULL;
	Node* p1 = pHead;
	Node* p2 = pHead->next;
	while (p1 != NULL)
	{
		p1->next = p0;
		p0 = p1;
		p1 = p2;
		if (p2 != NULL)
			p2 = p2->next;
	}
	return p0;
}

3完数:1000以内的完数,6的因子1,2,3 1+2+3=6

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int i, j, s;//i为可能的完数,j可能的因子,s因子和
	printf("1000以内的完数:\n");
	for (i = 2; i <= 1000; i++)
	{
		s = 0;//保证每次循环是s的初始值为0
		for (j = 1; j < i; j++)//为其本身
		{
			if (i%j == 0)//判断j是否为i的因子
				s += j;
		}
		if (s == i)//判断因子和原数是否相等
			printf("%3d是完数\n", i);
	}
	system("pause");
	return 0;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尘客-追梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值