一种有趣的C++链表反向打印方法
链表是一种以链接形式存储数据元素的数据结构。链表的每个节点都包含一个数据元素和一个链接。
打印链表的反转是一个常见的需要解决的问题。因此,在这里我们将学习一种有趣的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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP