在單連結串列的開頭插入節點

下面的程式碼將提示輸入數字並繼續將它們新增到連結列表的開頭。

/* This program will demonstrate inserting a node at the beginning of a linked list */

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

struct Node {
  int data;
  struct Node* next;
};

void insert_node (struct Node **head, int nodeValue);
void print_list (struct Node *head);

int main(int argc, char *argv[]) {
  struct Node* headNode;
  headNode = NULL; /* Initialize our first node pointer to be NULL. */
  size_t listSize, i;
  do {
    printf("How many numbers would you like to input?\n");
  } while(1 != scanf("%zu", &listSize));

  for (i = 0; i < listSize; i++) {
    int numToAdd;
    do {
      printf("Enter a number:\n");
    } while (1 != scanf("%d", &numToAdd));

    insert_node (&headNode, numToAdd);
    printf("Current list after your inserted node: \n");
    print_list(headNode);
  }

  return 0;
}

void print_list (struct Node *head) {
  struct node* currentNode = head;

  /* Iterate through each link. */
  while (currentNode != NULL) {
      printf("Value: %d\n", currentNode->data);
      currentNode = currentNode -> next;
  }
}

void insert_node (struct Node **head, int nodeValue) {
  struct Node *currentNode = malloc(sizeof *currentNode);
  currentNode->data = nodeValue;
  currentNode->next = (*head);

  *head = currentNode;
}

插入節點的說明

為了理解我們在開始時如何新增節點,讓我們看一下可能的場景:

  1. 該列表為空,因此我們需要新增一個新節點。在這種情況下,我們的記憶體看起來像這樣 HEAD 是指向第一個節點的指標:
| `HEAD` | --> NULL

currentNode->next = *headNode;currentNode->next 的值分配為 NULL,因為 headNode 最初的起始值為 NULL

現在,我們要將頭節點指標設定為指向當前節點。

  -----      -------------
 |HEAD | --> |CURRENTNODE| --> NULL /* The head node points to the current node */
  -----      -------------

這是通過*headNode = currentNode; 完成的

  1. 該列表已經填充; 我們需要在開頭新增一個新節點。為簡單起見,讓我們從 1 個節點開始:
 -----    -----------
 HEAD --> FIRST NODE --> NULL
 -----    -----------

使用 currentNode->next = *headNode,資料結構如下所示:

 ---------        -----    ---------------------
 currentNode -->  HEAD --> POINTER TO FIRST NODE --> NULL
 ---------        -----    ---------------------

其中,顯然需要改變,因為*headNode 應該指向 currentNode

 ----    -----------    ---------------
 HEAD -> currentNode -->     NODE       -> NULL
 ----    -----------    ---------------

這是通過*headNode = currentNode; 完成的