一種有趣的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