## 2013年3月12日 星期二

### [C 常見考題] Linked List Allocation Quiz

Preface:

Question:

2.     int data;
4. };
5.

1. PL createLL()
2. {
4.     PL head = NULL, rear = NULL;
5.     int i;
6.     for(i=0; i<6; i++)
7.     {
8.         PL newNode = malloc(sizeof(L));
9.         if(newNode==NULL)
10.         {
11.             printf("\t[Info] Memory error!\n");
12.             return NULL;
13.         }
14.         newNode->data = i;
15.         newNode->next = NULL;
16.         if(rear == NULL)
17.         {
18.             head = rear = newNode;
19.         }
20.         else
21.         {
22.             rear->next = newNode;
23.             rear = newNode;
24.         }
25.     }
27. }

Possible Sol:

1. PL createLL2()
2. {
6.     int i;
7.     for(i=0; i<6; i++)
8.     {
9.         *lastref = malloc(sizeof(L));
10.         (*lastref)->data = i;
11.         (*lastref)->next = NULL;
12.         lastref = &((*lastref)->next);
13.     }
14.
16. }

1. 使用 PPL 指向 head 的記憶體位置:

2. Memory allocation for struct LinkedList:

3. 移到 Linked List 當前 node 的下一個位置上 (方便下一個 loop 的 allocation)

4. 繼續 steps 2~3 直到 for loop 結束. (所以下一次為變數 *lastref 分配記憶體位置會指定到 變數 next 上面去!)

Complete Code Ref:

1. #include
2. #include
3.
5.     int data;
7. };
8.
12.
13. PL createLL()
14. {
16.     PL head = NULL, rear = NULL;
17.     int i;
18.     for(i=0; i<6; i++)
19.     {
20.         PL temp = malloc(sizeof(L));
21.         if(temp==NULL)
22.         {
23.             printf("\t[Info] Memory error!\n");
24.             return NULL;
25.         }
26.         temp->data = i;
27.         temp->next = NULL;
28.         if(rear == NULL)
29.         {
30.             head = rear = temp;
31.         }
32.         else
33.         {
34.             rear->next = temp;
35.             rear = temp;
36.         }
37.     }
39. }
40.
41. PL createLL2()
42. {
46.     int i;
47.     for(i=0; i<6; i++)
48.     {
49.         *lastref = malloc(sizeof(L));
50.         (*lastref)->data = i;
51.         (*lastref)->next = NULL;
52.         lastref = &((*lastref)->next);
53.     }
56. }
57.
59. {
62.     while(temp!=NULL)
63.     {
64.         printf("%d ", temp->data);
65.         temp = temp->next;
66.     }
67.     printf("\n");
68. }
69.
71. {
74.     while(temp!=NULL)
75.     {
79.     }
80. }
81.
82. int main()
83. {
87.     {
88.         printf("\t[Error] Fail!\n");
89.         return 0;
90.     }
93.     return 0;
94. }