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

โปรแกรม C พิมพ์ k โหนดสุดท้ายของ Linked List เรียงกลับ (Iterative)

โจทย์

พิมพ์ k โหนดสุดท้ายของ Linked List เรียงจากท้ายมาหน้า (reverse order) โดยใช้วิธี Iterative (ลูป)

ตัวอย่าง

Linked List: 29 → 34 → 43 → 56 → 88
k = 2
Output: 56 88

วิธีการ (ใช้ Stack Concept)

  1. นับจำนวนโหนดทั้งหมด (count)
  2. สร้างอาร์เรย์ขนาด count เก็บข้อมูลโหนดตามลำดับ
  3. เดินลิสต์อีกครั้ง ใส่ข้อมูลในอาร์เรย์ย้อนกลับ (index = --count)
  4. พิมพ์ k อิลิเมนต์แรกของอาร์เรย์ (คือ k โหนดสุดท้าย)

อัลกอริทึม

  1. โครงสร้างโหนด struct node {int data; struct node *next;}
  2. ฟังก์ชัน intoList() สร้างโหนด
  3. ฟังก์ชัน rev(head, count, k): นับโหนด → สร้าง array[count] → เติมข้อมูลย้อนกลับ → พิมพ์ array[0] ถึง array[k-1]
  4. 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