将链表进行反向输出:
#include <iostream>
typedef struct listnode {
int data;
struct listnode* next;
}listnode,*list;
void reserve(listnode *node)
{
//头部的后继节点置为空
//在转换后继节点的时候,需要提前将后继节点取出
if (node != nullptr)
{
listnode *head_node = new listnode;
head_node->data = 0;
head_node->next = node;
listnode *tmp_node = nullptr;
tmp_node = head_node->next;
while (tmp_node)
{
listnode *next_node = tmp_node;//当前节点的后继节点
tmp_node = tmp_node->next; //原当前节点的后后继节点
next_node->next = head_node; //后继节点指针反转
head_node = next_node;//node升级为后继节点
}
while (head_node)
{
printf("%d", head_node->data);
head_node = head_node->next;
if (head_node->data == 0)
{
head_node = nullptr;
}
}
}
}
int main()
{
listnode *next_node1 = new listnode;
listnode *next_node2 = new listnode;
listnode *next_node3 = new listnode;
listnode *next_node4 = new listnode;
listnode *next_node5 = new listnode;
next_node1->data = 1;
next_node1->next = next_node2;
next_node2->data = 2;
next_node2->next = next_node3;
next_node3->data = 3;
next_node3->next = next_node4;
next_node4->data = 4;
next_node4->next = next_node5;
next_node5->data = 5;
next_node5->next = nullptr;
reserve(next_node1);
}
|