要計算雙向鏈表的長度,可以使用以下算法:
下面是一個示例代碼:
#include <stdio.h>
#include <stdlib.h>
// 雙向鏈表的節點結構
typedef struct Node {
int data;
struct Node *prev; // 前驅節點指針
struct Node *next; // 后繼節點指針
} Node;
// 計算雙向鏈表的長度
int getLength(Node *head) {
int count = 0;
Node *current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int main() {
// 創建雙向鏈表
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;
// 計算鏈表的長度
int length = getLength(head);
printf("Length of the doubly linked list: %d\n", length);
// 釋放鏈表內存
Node *current = head;
while (current != NULL) {
Node *temp = current;
current = current->next;
free(temp);
}
return 0;
}
這段代碼中,我們首先創建了一個包含3個節點的雙向鏈表。然后使用getLength()
函數計算鏈表的長度,并將結果打印輸出。最后釋放了鏈表的內存。