Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีน่าสนใจพิมพ์ Linked List ย้อนหลังใน C++

ปัญหา

พิมพ์ Linked List แบบย้อนหลัง (Reverse) โดยไม่แก้โครงสร้าง List และท่องแค่ครั้งเดียว

ไอเดีย: ใช้ Carriage Return (\r)

Carriage Return (\r) ย้าย cursor กลับไปต้นบรรทัด โดยไม่ขึ้นบรรทัดใหม่

กลยุทธ์:

  1. หาความยาว List (n)
  2. ท่อง List ครั้งเดียว พร้อมพิมพ์แต่ละโหนดพร้อม \r
  3. ก่อนพิมพ์โหนดที่ j ให้พิมพ์ space จำนวน 2×(n-j) ช่อง
  4. ผลคือตัวเลขทับซ้อนกัน และเหลือแค่ตัวสุดท้ายของแต่ละตำแหน่ง → ได้ลำดับย้อนหลัง

ตัวอย่างโค้ด C++

#include <iostream>
#include <cstdlib>
using namespace std;

struct Node {
    int data;
    Node* next;
};

void push(Node** head, int data) {
    Node* newNode = new Node{data, *head};
    *head = newNode;
}

int printList(Node* head) {
    int count = 0;
    while (head) {
        cout << head->data << " ";
        head = head->next;
        count++;
    }
    cout << endl;
    return count;
}

void printReverse(Node** head_ref, int n) {
    Node* current = *head_ref;
    int j = 0;
    
    while (current != nullptr) {
        // พิมพ์ space เพื่อเลื่อนตำแหน่ง
        for (int i = 0; i < 2 * (n - j); i++)
            cout << " ";
        
        // พิมพ์ข้อมูลพร้อม carriage return
        cout << current->data << "\r";
        
        current = current->next;
        j++;
    }
    cout << endl; // ขึ้นบรรทัดใหม่ท้ายสุด
}

int main() {
    Node* head = nullptr;
    push(&head, 2);
    push(&head, 7);
    push(&head, 3);
    push(&head, 5);
    push(&head, 4);
    push(&head, 6);
    
    cout << "Original list: ";
    int n = printList(head); // 6 4 5 3 7 2
    
    cout << "Reversed list: ";
    printReverse(&head, n);  // 2 7 3 5 4 6
    
    return 0;
}

ผลลัพธ์

Original list: 6 4 5 3 7 2
Reversed list: 2 7 3 5 4 6

ข้อจำกัด

  • ทำงานได้เฉพาะ console ที่รองรับ \r อย่างถูกต้อง
  • อาจไม่ทำงานในบาง IDE หรือ redirected output
  • เป็น trick สำหรับการแข่งขัน/สอบ ไม่ใช่ best practice สำหรับ production code

วิธีมาตรฐานที่แนะนำ

  • Recursive (ใช้ stack เรียกฟังก์ชัน)
  • Stack explicit (เก็บ pointer แล้ว pop)
  • Reverse list แล้วพิมพ์ แล้ว reverse กลับ