倒序打印链表有以下几种常见思路:
- 先反转链表,然后遍历输出。
- 遍历一次链表,将地址加入数组,然后倒序遍历数组输出。
- 利用 stack,遍历一次将 Node 加入,然后 pop 输出。
- 利用递归。
下面是利用递归实现的示例代码:
struct Node
{
Node*next;
int data;
Node(){ func; }
};
Node* Insert(Node**p, int data)
{
if (data == 0)
{
(*p)->next = nullptr;
(*p)->data = 0;
return nullptr;
}
(*p)->next = new Node;
(*p)->data = data;
return Insert(&(*p)->next, data - 1);
}
void Print(Node*p)
{
if (p)
{
Print(p->next);
cout << p->data << " ";
}
}
int main()
{
Node* head = new Node;
head->data = 5;
Insert(&head, 5);
// while (head)
{
///cout << head->data << " ";
//head = head->next;
}
Print(head);
system("pause");
return 0;
}