代码:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct node //结构体
5 {
6 int data;
7 struct node *next;
8 };
9
10 struct node *createNode(int var);
11 void addNode(struct node **root, struct node *n);
12 void showLinkList(struct node *root);
13
14 int main(int argc, char *argv[])
15 {
16 struct node *head = NULL;
17 int i;
18 for(i = 0; i < 10; i++)
19 {
20 addNode(&head, createNode(i));
21 }
22 showLinkList(head);
23 return 0;
24 }
25
26 // 新建 节点
27 struct node *createNode(int var)
28 {
29 struct node *n = NULL;
30 n = (struct node *)malloc(sizeof(struct node));
31 n->data = var;
32 n->next = NULL;
33 return n;
34 }
35
36 //添加节点 至链表
37 void addNode(struct node **root, struct node *n)
38 {
39 struct node *temp;
40 temp = *root;
41 if( temp == NULL)
42 {
43 *root = n;
44 }
45 else
46 {
47 while(temp->next != NULL)
48 temp = temp->next;
49 temp->next = n;
50 }
51 }
52
53 //打印 链表
54 void showLinkList(struct node *root)
55 {
56 struct node *temp = root;
57 if(temp == NULL)
58 {
59 printf("ERROR: THE LINKLIST IS NULL.\n");
60 return;
61 }
62 while(temp != NULL)
63 {
64 printf("%d\n", temp->data);
65 temp = temp->next;
66 }
67 }
执行:
结构体赋值
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct node
5 {
6 int data;
7 };
8
9 void addNode_pointer(struct node **n, int var)
10 {
11 *n = (struct node *)malloc(sizeof(struct node));
12 (*n)->data = var;
13 }
14
15 void addNode_var(struct node *n, int var)
16 {
17 //*n = (struct node *)malloc(sizeof(struct node));
18 n->data = var;
19 }
20
21 struct node *addNode(int var)
22 {
23 struct node *n = NULL;
24 n = (struct node *)malloc(sizeof(struct node));
25 n->data = var;
26 return n;
27 }
28
29 int main(int argc, char *argv[])
30 {
31 struct node *n0 = NULL;
32 struct node *n1 = NULL;
33 struct node *n2 = NULL;
34 struct node n3;
35 struct node n4;
36 // struct node n5;
37
38 n0 = (struct node *)malloc(sizeof(struct node));
39 n0->data = 0;
40 printf("n0->data = %d\n", n0->data);
41
42 addNode_pointer(&n1, 1);
43 printf("n1->data = %d\n", n1->data);
44
45 addNode_pointer(&n2, 2);
46 printf("n2->data = %d\n", (*n2).data);
47
48 n3.data = 3;
49 printf("n3->data = %d\n", n3.data);
50
51 addNode_var(&n4, 4);
52 printf("n4->data = %d\n", n4.data);
53
54 printf("n5->data = %d\n", addNode(5)->data);
55 return 0;
56 }
执行: