链表反转C++代码,附加打印逆序链表(不进行反转)代码。
测试用例:
5
2 3 4 10 5
1
4
1.非递归实现
思路:需要三个指针p1、p2、p3,分别指向上一个节点、当前节点与缓存的下一个节点,每次循环执行操作:
(----表示为连接,<—表示左连接,xx表示未使用指针)
缓存与反转:p1<—p2----p3
指针右移: xx-----p1----p2
代码:(核心代码为34~45行)
//链表反转-非递归
#include<iostream>
using namespace std;
struct Node
{
int value;
Node* next;
};
int main()
{
int n; //链表节点个数
while (cin>>n)
{
if (n <= 0) { continue; }
//链表创建
Node* head = new Node;
cin >> head->value;
head->next = nullptr;
Node* p = head;
for (int i = 1; i < n; i++)
{
Node* tmp = new Node;
cin >> tmp->value;
tmp->next = nullptr;
p->next = tmp;
p = p -> next;
}
//链表反转-非递归
Node* p1 = nullptr; //上一个节点的指针
Node* p2 = head; //当前节点的指针
Node* p3 = nullptr; //用于缓存下一个节点的指针
while (p2!=nullptr)
{
p3 = p2->n