c語言雙向鏈表的長(zhǎng)度如何計(jì)算

小億
104
2023-12-27 15:36:28
欄目: 編程語言

要計(jì)算雙向鏈表的長(zhǎng)度,可以使用以下算法:

  1. 定義一個(gè)變量count并初始化為0,用于計(jì)數(shù)。
  2. 從鏈表的頭節(jié)點(diǎn)開始,依次遍歷鏈表的每個(gè)節(jié)點(diǎn)。
  3. 每次遍歷一個(gè)節(jié)點(diǎn),count加1。
  4. 當(dāng)遍歷到鏈表的最后一個(gè)節(jié)點(diǎn)時(shí),count的值即為鏈表的長(zhǎng)度。
  5. 返回count作為鏈表的長(zhǎng)度。

下面是一個(gè)示例代碼:

#include <stdio.h>
#include <stdlib.h>

// 雙向鏈表的節(jié)點(diǎn)結(jié)構(gòu)
typedef struct Node {
    int data;
    struct Node *prev; // 前驅(qū)節(jié)點(diǎn)指針
    struct Node *next; // 后繼節(jié)點(diǎn)指針
} Node;

// 計(jì)算雙向鏈表的長(zhǎng)度
int getLength(Node *head) {
    int count = 0;
    Node *current = head;
    while (current != NULL) {
        count++;
        current = current->next;
    }
    return count;
}

int main() {
    // 創(chuàng)建雙向鏈表
    Node *head = (Node *)malloc(sizeof(Node));
    head->data = 1;
    head->prev = NULL;
    Node *node2 = (Node *)malloc(sizeof(Node));
    node2->data = 2;
    node2->prev = head;
    head->next = node2;
    Node *node3 = (Node *)malloc(sizeof(Node));
    node3->data = 3;
    node3->prev = node2;
    node2->next = node3;
    node3->next = NULL;

    // 計(jì)算鏈表的長(zhǎng)度
    int length = getLength(head);
    printf("Length of the doubly linked list: %d\n", length);

    // 釋放鏈表內(nèi)存
    Node *current = head;
    while (current != NULL) {
        Node *temp = current;
        current = current->next;
        free(temp);
    }
    return 0;
}

這段代碼中,我們首先創(chuàng)建了一個(gè)包含3個(gè)節(jié)點(diǎn)的雙向鏈表。然后使用getLength()函數(shù)計(jì)算鏈表的長(zhǎng)度,并將結(jié)果打印輸出。最后釋放了鏈表的內(nèi)存。

0