下面一共写了三种插入方式:

  • push : 从头部插入
  • insertAfter : 给定一个指针中的结点,插入到该结点的后面
  • append : 从尾部插入 ```

    include

    include

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

typedef struct Node node;

void printList(struct Node* n) { while(n != NULL) { printf(“ %d “, n->data); n = n->next; } }

// insert a new node on the front of the list. void push(node* head_ref, int new_data) { // 1. allocate node node new_node = (node)malloc(sizeof(node)); // 2. put in the data new_node->data = new_data; // 3. make next of new node as head new_node->next = head_ref; // 4. move the head to point to the new node *head_ref = new_node; }

// insert a new node after the given prev_node void inserAfter(node* prev_node, int new_data) { // 1. check if the given prev_node is NULL if (prev_node == NULL) { printf(“the given pervious node cannot be NULL”); return ; }

  1. // 2. allocate new node
  2. node *new_node = (node*)malloc(sizeof(node));
  3. // 3. put in the data
  4. new_node->data = new_data;
  5. // 4. make next of new node as next of prev_node
  6. new_node->next = prev_node->next;
  7. // 5. move the next of prev_node as new_node
  8. prev_node->next = new_node;

}

// append a new node at the end void append(node* head_ref, int new_data) { // 1. allocate node node new_node = (node*)malloc(sizeof(node));

  1. node *last = *head_ref; // used in step 5
  2. // 2. put in the data
  3. new_node->data = new_data;
  4. // 3. This new node is going to be the last node, so make next of it as NULL
  5. new_node->next = NULL;
  6. // 4. If the Linked list is empty, then make the new node as head
  7. if (*head_ref == NULL) {
  8. *head_ref = new_node;
  9. return ;
  10. }
  11. // 5. Else traverse till the last node
  12. // 遍历 直到
  13. while(last->next != NULL) last = last->next;
  14. // 6. Change the next of last node
  15. last->next = new_node;

}

// append a new array at the end void appendToArray(node* head_ref, int a, int len) { if (len <= 0) { printf(“the given len must be greater than or equal to 0”); return ; } node temp = (node)malloc(sizeof(node)); node* new_head = temp;

  1. temp->data = a[0];
  2. temp->next = NULL;
  3. for(int i=1; i<len; ++i) {
  4. node *new_node = (node*)malloc(sizeof(node));
  5. new_node->data = a[i];
  6. new_node->next = NULL;
  7. temp->next = new_node;
  8. temp = new_node;
  9. }
  10. if (*head_ref == NULL) {
  11. *head_ref = new_head;
  12. return ;
  13. }
  14. node* last = *head_ref;
  15. while(last->next != NULL) {
  16. last = last->next;
  17. }
  18. last->next = new_head;

}

int main() { struct Node* head = NULL;

  1. push(&head, 1);
  2. push(&head, 2);
  3. push(&head, 3);
  4. inserAfter(head->next, 5);
  5. append(&head, 54);
  6. printList(head);
  7. return 0;

}

```