โจทย์
พิมพ์ k โหนดสุดท้ายของ Linked List เรียงจากท้ายมาหน้า (reverse order) โดยใช้วิธี Iterative (ลูป)
ตัวอย่าง
Linked List: 29 → 34 → 43 → 56 → 88 k = 2 Output: 56 88
วิธีการ (ใช้ Stack Concept)
- นับจำนวนโหนดทั้งหมด (count)
- สร้างอาร์เรย์ขนาด count เก็บข้อมูลโหนดตามลำดับ
- เดินลิสต์อีกครั้ง ใส่ข้อมูลในอาร์เรย์ย้อนกลับ (index = --count)
- พิมพ์ k อิลิเมนต์แรกของอาร์เรย์ (คือ k โหนดสุดท้าย)
อัลกอริทึม
- โครงสร้างโหนด struct node {int data; struct node *next;}
- ฟังก์ชัน intoList() สร้างโหนด
- ฟังก์ชัน rev(head, count, k): นับโหนด → สร้าง array[count] → เติมข้อมูลย้อนกลับ → พิมพ์ array[0] ถึง array[k-1]
- main(): สร้างลิสต์ เรียก rev(head, 0, 3)
โค้ดภาษา C
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node* intoList(int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void rev(struct node* head, int count, int k) {
struct node* temp1 = head;
while (temp1 != NULL) {
count++;
temp1 = temp1->next;
}
int array[count], temp2 = count, i;
temp1 = head;
while (temp1 != NULL) {
array[--temp2] = temp1->data;
temp1 = temp1->next;
}
for (i = 0; i < k; i++)
printf("%d ", array[i]);
}
int main() {
printf("\nreverse of a list is : ");
struct node* head = intoList(9);
head->next = intoList(76);
head->next->next = intoList(13);
head->next->next->next = intoList(24);
head->next->next->next->next = intoList(55);
head->next->next->next->next->next = intoList(109);
int k = 3, count = 0;
rev(head, count, k);
return 0;
}ผลลัพธ์
reverse of a list is : 109 55 24