Delete last n node 教學與筆記。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node * next; }; void push (struct Node** head_ref, int input) { struct Node * new = (struct Node*)malloc (sizeof (struct Node)); new -> data = input; new -> next = *head_ref; *head_ref = new ; } void print_list (struct Node* curr) { while (curr != NULL ){ printf ("%d " , curr->data); curr = curr -> next; } printf ("\n" ); } int store_list_to_array (struct Node* curr, struct Node** ptr_arr) { int total_size = 0 ; while (curr != NULL ){ *ptr_arr = curr; curr = curr -> next; ptr_arr++; total_size++; } return total_size; } void main () { struct Node * head = NULL ; push (&head, 7 ); push (&head, 6 ); push (&head, 5 ); push (&head, 4 ); push (&head, 3 ); push (&head, 2 ); push (&head, 1 ); struct Node * ptr_arr[100 ]; int list_size = store_list_to_array (head, ptr_arr); for (int i = 0 ; i < list_size; i++){ printf ("%d " , ptr_arr[i]->data); } printf ("\n" ); int n = 2 ; ptr_arr[list_size-n-1 ]->next = ptr_arr[list_size-n+1 ]; free (ptr_arr[list_size-n]); print_list (head); }
結果 :
n = 2 example
1 2 1 2 3 4 5 6 7 1 2 3 4 5 7