Advertisement
Guest User

new

a guest
Jul 22nd, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4.  
  5. #define NEWNODE (Node*)malloc(sizeof(Node))
  6.  
  7. //宣告單向連結節點結構
  8. typedef struct SNode
  9. {
  10.     int val;//存值
  11.     struct SNode* next = NULL;//指向節點的下一個位址
  12. }Node;
  13. //全域變數
  14. Node* head = NULL;//指向第一個節點值
  15.  
  16. int is_empty()//判斷節點是否為空
  17. {
  18.     return head == NULL;//如果head指向NULL?回傳1:回傳0
  19. }
  20.  
  21. Node* end()//回傳最後一節點位址
  22. {
  23.     Node* iterator = head;//選代器指向head
  24.     while(iterator->next)//下一節點未指向NULL
  25.         iterator = iterator->next;
  26.     return iterator;
  27. }
  28.  
  29. void append(int _val)//加入節點至尾巴
  30. {
  31.     if(is_empty())
  32.     {
  33.         head = NEWNODE;//配
  34.         assert(head);//防止記憶體配置失敗
  35.         head->val = _val;
  36.     }else
  37.     {
  38.         Node* last = end();//last指向最後節點
  39.         last->next = NEWNODE;//在最後節點的下一個位址配置節點
  40.         assert(last->next);//防止記憶體配置失敗
  41.         last->next->val = _val;
  42.     }
  43. }
  44.  
  45. void print()
  46. {
  47.     if(is_empty())//如果資料為空
  48.     {
  49.         printf("list is empty\n");
  50.     }else
  51.     {
  52.         Node* iterator = head;//選代器指向head
  53.         while(iterator)
  54.         {
  55.             printf("%d,",iterator->val);//輸出值
  56.             iterator = iterator->next;
  57.         }
  58.         printf("\n");
  59.     }
  60. }
  61.  
  62. int main()
  63. {
  64.     print();
  65.     append(10);
  66.     print();
  67.     append(4);
  68.     print();
  69.     append(8);
  70.     print();
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement