C++迴圈連結串列節點計數
給定一個包含節點的迴圈連結串列,任務是計算迴圈連結串列中存在的節點數。
迴圈連結串列是連結串列的一種變體,其中第一個元素指向最後一個元素,最後一個元素指向第一個元素。單鏈表和雙鏈表都可以轉換為迴圈連結串列。
在下面的程式中,我們將單鏈表實現為迴圈連結串列,以計算其中的節點數。
例如
Input − nodes-: 20, 1, 2, 3, 4, 5 Output − count of nodes are-: 6 Input − nodes-: 20, 1, 2, 3, 4, 5, 7, 8, 9, 12 Output − count of nodes are-: 10
下面程式中使用的方案如下:
建立單鏈表的結構,包括節點儲存的地址和資料。
建立一個push()函式,用於將資料插入節點。
在最後一個節點中,儲存第一個節點的地址,使單鏈表充當迴圈連結串列。
建立一個計數函式,用於計算迴圈連結串列中存在的節點總數。
示例
#include <stdio.h> #include <stdlib.h> /* Defining a node */ struct node { int data; struct node* next; }; // Inserting node in Circular list void push(struct node** head_ref, int data){ struct node* ptr1 = (struct node*)malloc(sizeof(struct node)); struct node* temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; // going to the last node to insert new element. if (*head_ref != NULL){ while (temp->next != *head_ref){ temp = temp->next; } temp->next = ptr1; } else{ ptr1->next = ptr1; //for first node } *head_ref = ptr1; } // Function to count the number of nodes int count_fun(struct node* head){ struct node* temp = head; int result = 0; if (head != NULL){ do { temp = temp->next; result++; } while (temp != head); } return result; } int main(){ /* Initializing the list as empty */ struct node* head = NULL; push(&head, 10); push(&head, 20); push(&head, 30); push(&head, 40); printf("count of nodes are: %d", count_fun(head)); return 0; }
輸出
如果執行上述程式碼,將生成以下輸出:
count of nodes are: 4
廣告