Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Traversing and Displaying a Linked List | Implementing Data Structures
C Structs
セクション 5.  4
single

single

bookTraversing and Displaying a Linked List

メニューを表示するにはスワイプしてください

After we have learned how to create and connect nodes, we need to check that such a list works correctly!

To do this, let's write a simple function that will display the entire list.

The function will accept a pointer to the memory area where the head (first) node of the list is stored.

void printList(struct Node* head) {}

After which a temporary node current will be created, with which we will go through the entire list. The content of the current node will be equal to the content of the current list node.

struct Node* current = head;

To iterate through the list, we use the while(){} loop with the necessary condition, namely, until a node is found whose next field is NULL.

Note
Note

The temp (temporary) node plays the role of a buffer node. It is needed to temporarily store (and delete) the contents of the current node. If we immediately clear the current node, we will lose connection with the next node, which means access to the list will be lost.

while (current != NULL) { }
printf("\n");

Inside the loop, we will display the contents of the data field of the current node and change the next field to move to the next node.

printf("%d ", current->data);
current = current->next;

As soon as a node is found whose next field equal NULL, the loop will stop displaying the contents of the nodes and the function will end.

タスク

スワイプしてコーディングを開始

Implement a simple singly linked list with dynamic memory allocation. The task is to complete the functions printList and freeList.

  1. Implement a function printList with a single parameter struct Node* head.
    • Inside printList, declare a variable current and initialize it to head.
    • Use a while loop to iterate as long as current is not NULL.
    • In each iteration, print the data field of current and move current to the next node.
    • After the loop, print a newline character to separate the output.
  2. Inside freeList, declare a variable current and initialize it to head.
    • Use a while loop to iterate as long as current is not NULL.
    • Inside the loop, store current in a temporary variable temp.
    • Move current to the next node.
    • Free the memory allocated for temp.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  4
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt