獲取鏈表長度(迭代法和遞歸法)
迭代法
1、設定一個計數器,初始值為0
2、初始化current到頭節點
3、如果current不為null進行以下循環
a) current = current -> next b) count++;
4、返回計數器
c語言:
/* Counts no. of nodes in linked list */
int getCount(struct Node* head)
{
int count = 0; // Initialize count
struct Node* current = head; // Initialize current
while (current != NULL) { count++; current = current->next; } return count; }
java:
/* Returns count of nodes in linked list */
public int getCount()
{
Node temp = head; int count = 0; while (temp != null) { count++; temp = temp.next; } return count; }
c#:
/* Returns count of nodes in linked list */
public int getCount()
{
Node temp = head; int count = 0; while (temp != null) { count++; temp = temp.next; } return count; }
遞歸法
int getCount(head) 1) If head is NULL, return 0. 2) Else return 1 + getCount(head->next)
c語言:
/* Counts the no. of occurrences of a node
(search_for) in a linked list (head)*/
int getCount(struct Node* head)
{
// Base case
if (head == NULL) return 0; // count is 1 + count of remaining list return 1 + getCount(head->next); }
java
/* Returns count of nodes in linked list */
public int getCountRec(Node node)
{
// Base case
if (node == null) return 0; // Count is this node plus rest of the list return 1 + getCountRec(node.next); }
c#
/* Returns count of nodes in linked list */
public int getCountRec(Node node)
{
// Base case
if (node == null) return 0; // Count is this node plus rest of the list return 1 + getCountRec(node.next); }
文章來源:https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/