链表是一种以链表形式存储数据元素的数据结构。链表的每个节点都有一个数据元素和一个链接。
链表的反向打印是解决问题时需要解决的常见问题。因此,这里我们将学习一种有趣的方法,以c ++编程语言打印反向链接列表。
通常,打印反向链接列表需要在列表中进行修改或对列表进行多次遍历,但是此方法不需要任何此类操作,并且仅遍历链接列表一次。
此方法的逻辑是使用回车键来反向打印字符串。回车是打印机的命令(在显示时为光标),以保留行上的位置并移至屏幕中的某个特定位置。现在,逻辑是前进n(列表的长度),以便为要打印的列表元素留出空间。在要打印的第一个元素之前应保留n -1空格。然后n-2代表第二个,依此类推。
现在让我们看一个程序来说明这个概念,
#include<stdio.h> #include<stdlib.h> #include<iostream> using namespace std; struct Node { int data; struct Node* next; }; void printReverse(struct Node** head_ref, int n) ; void push(struct Node** head_ref, int new_data) ; int printList(struct Node* head) ; int main(){ struct Node* head = NULL; push(&head, 2); push(&head, 7); push(&head, 3); push(&head, 5); push(&head, 4); push(&head, 6); printf("Given linked list:\n"); int n = printList(head); printf("\nReversed Linked list:\n"); printReverse(&head, n); return 0; } void printReverse(struct Node** head_ref, int n){ int j = 0; struct Node* current = *head_ref; while (current != NULL) { for (int i = 0; i < 2 * (n - j); i++) cout<<" "; cout<<current->data<<"\r"; current = current->next; j++; } } void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } int printList(struct Node* head){ int i = 0; struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; i++; } return i; }
输出结果
Given linked list: 6 4 5 3 7 2 Reversed Linked list: 2 7 3 5 4 6