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

โปรแกรม C พิมพ์โหนดสลับของ Linked List (Iterative Method)

โจทย์

พิมพ์โหนดสลับของ Linked List (โหนดที่ 0, 2, 4, ...) โดยใช้วิธี Iterative (ลูป)

ตัวอย่าง

Input: 29 → 34 → 43 → 56 → 88
Output: 29 43 88

วิธีการ

  1. ใช้ counter เริ่มจาก 0
  2. เดินผ่านลิสต์ด้วย while (head != NULL)
  3. ถ้า count % 2 == 0 ให้พิมพ์ head->data
  4. count++, head = head->next

อัลกอริทึม

  1. โครงสร้างโหนด struct node {int data; struct node* next;}
  2. ฟังก์ชัน alternate(head): count=0, while(head){ if(count%2==0) print; count++; head=head->next; }
  3. ฟังก์ชัน push(&head, data) เพิ่มโหนดหน้าลิสต์
  4. 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