下面一共写了三种插入方式:
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 ; }
// 2. allocate new node
node *new_node = (node*)malloc(sizeof(node));
// 3. put in the data
new_node->data = new_data;
// 4. make next of new node as next of prev_node
new_node->next = prev_node->next;
// 5. move the next of prev_node as new_node
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));
node *last = *head_ref; // used in step 5
// 2. put in the data
new_node->data = new_data;
// 3. This new node is going to be the last node, so make next of it as NULL
new_node->next = NULL;
// 4. If the Linked list is empty, then make the new node as head
if (*head_ref == NULL) {
*head_ref = new_node;
return ;
}
// 5. Else traverse till the last node
// 遍历 直到
while(last->next != NULL) last = last->next;
// 6. Change the next of last node
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;
temp->data = a[0];
temp->next = NULL;
for(int i=1; i<len; ++i) {
node *new_node = (node*)malloc(sizeof(node));
new_node->data = a[i];
new_node->next = NULL;
temp->next = new_node;
temp = new_node;
}
if (*head_ref == NULL) {
*head_ref = new_head;
return ;
}
node* last = *head_ref;
while(last->next != NULL) {
last = last->next;
}
last->next = new_head;
}
int main() { struct Node* head = NULL;
push(&head, 1);
push(&head, 2);
push(&head, 3);
inserAfter(head->next, 5);
append(&head, 54);
printList(head);
return 0;
}
```