用于打印链接列表的反向而不实际反转的 C++ 程序
给定一个链表,使用递归函数打印它的反向。例如,如果给定的链表是 1->2->3->4,那么输出应该是 4->3->2->1。
请注意,问题只是关于打印反向。要反转列表本身,请参阅此
难度级别:新手
算法:
printReverse(head)
1. call print reverse for head->next
2. print head->data
执行:
C++
// C++ program to print reverse of a linked list
#include
using namespace std;
// Link list node
class Node
{
public:
int data;
Node* next;
};
// Function to reverse the
// linked list
void printReverse(Node* head)
{
// Base case
if (head == NULL)
return;
// Print the list after head node
printReverse(head->next);
// After everything else is printed,
// print head
cout << head->data << " ";
}
// UTILITY FUNCTIONS
/* Push a node to linked list.
Note that this function
changes the head */
void push(Node** head_ref,
char new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list off the
// new node
new_node->next = (*head_ref);
// Move the head to point to
// the new node
(*head_ref) = new_node;
}
// Driver code
int main()
{
// Let us create linked list
// 1->2->3->4
Node* head = NULL;
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printReverse(head);
return 0;
}
// This code is contributed by rathbhupendra
输出:
4 3 2 1
时间复杂度: O(n)
有关详细信息,请参阅有关打印链接列表的反向而不实际反转的完整文章!