โจทย์
พิมพ์โหนดสลับของ Linked List (โหนดที่ 0, 2, 4, ...) โดยใช้วิธี Iterative (ลูป)
ตัวอย่าง
Input: 29 → 34 → 43 → 56 → 88 Output: 29 43 88
วิธีการ
- ใช้ counter เริ่มจาก 0
- เดินผ่านลิสต์ด้วย while (head != NULL)
- ถ้า count % 2 == 0 ให้พิมพ์ head->data
- count++, head = head->next
อัลกอริทึม
- โครงสร้างโหนด struct node {int data; struct node* next;}
- ฟังก์ชัน alternate(head): count=0, while(head){ if(count%2==0) print; count++; head=head->next; }
- ฟังก์ชัน push(&head, data) เพิ่มโหนดหน้าลิสต์
- main(): push 5 ค่า เรียก alternate()
โค้ดภาษา C
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
void alternate(struct node* head) {
int count = 0;
while (head != NULL) {
if (count % 2 == 0)
printf(" %d ", head->data);
count++;
head = head->next;
}
}
void push(struct node** header, int newdata) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = newdata;
newnode->next = (*header);
(*header) = newnode;
}
int main() {
printf("alternate nodes are :");
struct node* head = NULL;
push(&head, 1);
push(&head, 9);
push(&head, 10);
push(&head, 21);
push(&head, 80);
alternate(head);
return 0;
}ผลลัพธ์
alternate nodes are : 80 10 1
หมายเหตุ: push() เพิ่มที่หัวลิสต์ ดังนั้นลิสต์จริงคือ 80→21→10→9→1 โหนดสลับคือ 80, 10, 1