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;
}