some Pointer and Struct practicing
链表由两部分组成,一部分是指针区,一部分是数据区,这里要说的是单链表,指针区仅仅只是下一个节点的地址,为了简化程序,数据区也只设置一个整型变量
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| typedef struct node{ int data; struct node *next; }node;
node * node_init(){ node * head = (node *)malloc(sizeof(node)); head -> next = NULL; head -> data = -1; return head; }
node * node_add(node *head, int data){ node * newnode = (node *)malloc(sizeof(node)); if(!newnode)return NULL; node *p = head; while(p -> next != NULL )p = p -> next; p -> next = newnode; newnode -> next = NULL; newnode -> data = data; return newnode; }
void list_print(node *head){ node *p = head; int x = 0; while(p != NULL){ printf("node(%d):%d\n", x, p -> data); p = p -> next; x++; } }
node * node_insert(node *head, int i,int data){ node * newnode = (node *)malloc(sizeof(node)); if(!newnode)return NULL; newnode -> data = data; node * p = head; while(i > 0 && p -> next != NULL){ p = p -> next; i--; } newnode -> next = p -> next; p -> next = newnode; return newnode; }
void node_del(node *head, int i){ node *p1 = head; node *p2; if(i == 0)i++; while(i > 0 && p1 -> next != NULL){ i--; p2 = p1; p1 = p1 -> next; } p2 -> next = p1 -> next; free(p1); }
int list_length(node *head){ node *p = head; int count = 0; while(p != NULL){ p = p -> next; count++; } return count; }
void list_del(node *head){ node * p1 = head; node * p2; while(p1 != NULL){ p2 = p1; p1 = p1 -> next; free(p2); } }
node * node_modify(node *head, int i, int data){ node *p = head; while(i > 0){ if(p -> next == NULL)return NULL; p = p -> next; i--; } p -> data = data; return p; }
|