Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

addFirst

الدرس 5 من 14 في دورة القائمة المترابطة المزدوجة - سلسلة هياكل البيانات #6 على Coddy.

challenge icon

التحدي

سهل

أضف طريقة addFirst إلى فئة DoublyLinkedList.

تستقبل هذه الطريقة قيمة صحيحة value وتقوم بإدراج عقدة جديدة تحمل تلك القيمة في مقدمة القائمة. تأكد من ربط كلا اتجاهي الوصلة (prev في الرأس القديم، و next في العقدة الجديدة)، وتحديث tail إذا كانت القائمة فارغة.

جرّب بنفسك

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doublylinkedlist.h"

int main() {
    DoublyLinkedList ll;
    DoublyLinkedList_init(&ll);
    char line[256];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "state") == 0) printf("%s %s %d\n", ll.head == NULL ? "true" : "false", ll.tail == NULL ? "true" : "false", ll.count);
        if (strcmp(cmd, "count") == 0) printf("%d\n", ll.count);
        if (strcmp(cmd, "headValue") == 0) printf("%d\n", Node_getValue(ll.head));
        if (strcmp(cmd, "tailValue") == 0) printf("%d\n", Node_getValue(ll.tail));
        if (strcmp(cmd, "addFirst") == 0) {
            char* arg = strtok(NULL, " \t");
            DoublyLinkedList_addFirst(&ll, atoi(arg));
        }
    }
    return 0;
}

جميع دروس القائمة المترابطة المزدوجة - سلسلة هياكل البيانات #6