รายการที่เชื่อมโยงเป็นโครงสร้างข้อมูลที่จัดเก็บองค์ประกอบข้อมูลในรูปแบบที่เชื่อมโยง แต่ละโหนดของรายการที่เชื่อมโยงมีองค์ประกอบข้อมูลและลิงก์
พิมพ์ย้อนกลับของรายการที่เชื่อมโยงเป็นปัญหาทั่วไปที่ต้องแก้ไขในการแก้ปัญหา ดังนั้น ในที่นี้เราจะได้เรียนรู้วิธีที่น่าสนใจในการพิมพ์ย้อนกลับของรายการที่เชื่อมโยงในภาษาการเขียนโปรแกรม c++
โดยทั่วไปแล้วการพิมพ์รายการที่เชื่อมโยงแบบย้อนกลับจำเป็นต้องแก้ไขในรายการหรือการสำรวจหลายครั้งของรายการ แต่วิธีนี้ไม่ต้องการสิ่งดังกล่าวและข้ามผ่านรายการที่เชื่อมโยงเพียงครั้งเดียวเท่านั้น
ตรรกะของวิธีนี้คือใช้การขึ้นบรรทัดใหม่เพื่อพิมพ์สตริงย้อนกลับ Carriage return เป็นคำสั่งไปยังเครื่องพิมพ์ (เคอร์เซอร์ในกรณีที่แสดง) เพื่อออกจากตำแหน่งในบรรทัดและย้ายไปยังตำแหน่งเฉพาะในหน้าจอเดียว ตอนนี้ ตรรกะคือการเลื่อน n (ความยาวของรายการ) ออกจากพื้นที่สำหรับองค์ประกอบ t ehe ของรายการที่จะพิมพ์ ควรมีช่องว่าง 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