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

โปรแกรม C พิมพ์โหนดของ Linked List ตามดัชนีที่กำหนด

โจทย์

Linked List ไม่มีดัชนี (index) ตรงๆ ต้องเดินผ่าน (traverse) เพื่อหาโหนดที่ตำแหน่งที่กำหนด

ตัวอย่าง

Linked List: 29 → 34 → 43 → 56 → 88
Indexes: 1, 2, 4
Output: 34 43 88

วิธีการ

  1. ใช้ pointer เดินผ่านลิสต์ พร้อมตัวนับ (counter) เริ่มจาก 0
  2. เมื่อ counter ตรงกับ index ที่ต้องการ ให้พิมพ์ข้อมูลโหนดนั้น
  3. ทำซ้ำสำหรับทุก index ที่ต้องการ

อัลกอริทึม

  1. โครงสร้างโหนด: struct node {int data; struct node *next;}
  2. ฟังก์ชัน intoList() สร้างโหนดใหม่
  3. ฟังก์ชัน displayList() แสดงลิสต์ทั้งหมด
  4. ฟังก์ชัน search(key, head) คืนค่า index ของ key (หรือ -1 ถ้าไม่เจอ)
  5. ใน main(): สร้างลิสต์ เรียก displayList() และ search()

โค้ดภาษา 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 displayList(struct node *catchead) {
    struct node *temp;
    if (catchead == NULL) {
        printf("List is empty.\n");
        return;
    }
    printf("elements of list are : ");
    temp = catchead;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int search(int key, struct node *head) {
    int index = 0;
    struct node *newnode = head;
    while (newnode != NULL && newnode->data != key) {
        index++;
        newnode = newnode->next;
    }
    return (newnode != NULL) ? index : -1;
}

int main() {
    int index;
    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);
    
    displayList(head);
    index = search(24, head);
    if (index >= 0) printf("%d found at position %d\n", 24, index);
    else printf("%d not found in the list.\n", 24);
    
    index = search(55, head);
    if (index >= 0) printf("%d found at position %d\n", 55, index);
    else printf("%d not found in the list.\n", 55);
    return 0;
}

ผลลัพธ์

elements of list are : 9 76 13 24 55 109
24 found at position 3
55 found at position 4