โจทย์
พิมพ์ Linked List เรียงจากท้ายมาหน้า (reverse order) แต่ ไม่เปลี่ยนลำดับโหนดจริง ใช้ Recursive
ตัวอย่าง
Input: 29 → 34 → 43 → 56 Output: 56 43 34 29
วิธีการ Recursive
- ฟังก์ชัน reverse(head): ถ้า head == NULL return
- เรียก reverse(head->next) ก่อน (ไปจนท้ายลิสต์)
- พิมพ์ head->data (พิมพ์ขณะกลับมาจาก recursion)
- ลำดับโหนดในหน่วยความจำไม่เปลี่ยนแปลง
อัลกอริทึม
- โครงสร้างโหนด struct node {int data; node* next;}
- ฟังก์ชัน reverse(node* head): base case head==NULL return; recursive call reverse(head->next); print head->data
- ฟังก์ชัน push(&head, data) เพิ่มโหนดหน้าลิสต์
- main(): push 4 ค่า เรียก reverse(head)
โค้ดภาษา C
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
node* next;
};
void reverse(node* head) {
if (head == NULL) return;
reverse(head->next);
printf("%d ", head->data);
}
void push(node** header, char newdata) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = newdata;
newnode->next = (*header);
(*header) = newnode;
}
int main() {
node* head = NULL;
push(&head, 56);
push(&head, 43);
push(&head, 34);
push(&head, 29);
reverse(head);
return 0;
}ผลลัพธ์
reverse of a linked list 56 43 34 29
ข้อดี: ไม่ต้องแก้ไข pointer ของลิสต์ ใช้ call stack จัดการลำดับการพิมพ์