Pages

2010年10月2日 星期六

Linking-List Implement

[轉載] from: http://www.cnblogs.com/oomusou/archive/2008/03/22/1117686.html
Abstraction
使用C語言簡單的實現linked list,並用C++的std::vector實作出相同的功能作比較。
Introduction
學習資料結構,第一個要學的就是linked list,本文示範最簡單的linked list實現,包含建立與顯示,可把它當成linked list的標準範本,畢竟步驟都差不多。
一個基本的問題:為什麼需要linked list?若要將大量資料存到記憶體,你會想到什麼?第一個想到的就是array,但C語言是個靜態語言,array必須事先宣告大小,這樣compiler才能進行最佳化,若到時候沒用這麼多記憶體,就白白浪費記憶體了。或許你會說array可以配合malloc()變成動態array,但前提是你必須告訴malloc()要建立多大的array,若連要建立多大的陣列也不確定,而是在run-time看有多少資料就建立多大,這時連malloc()的動態array也不能用了,此時就得靠linked list。
linked list是資料結構的基礎,基本上就是靠struct如火車車廂那樣連在一起,run-time有需要時,在動態掛一個struct上去。

For C語言:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define SLEN 255
  5.  
  6. struct list {
  7. int no;
  8. char name[SLEN];
  9. struct list *next;
  10. };
  11. int main() {
  12. int no;
  13. char s[255];
  14. struct list *head = NULL;
  15. struct list *current = NULL;
  16. struct list *prev = NULL;
  17.  
  18. while(1) {
  19. printf("No. = ");
  20. scanf("%d", &no);
  21. if (no == 0)
  22. break;
  23.  
  24. printf("Name = ");
  25. scanf("%s", s);
  26.  
  27. current = (struct list *)malloc(sizeof(struct list));
  28. if (current == NULL)
  29. exit(EXIT_FAILURE);
  30.  
  31. current->next = NULL;
  32.  
  33. current->no = no;
  34. strncpy(current->name, s, SLEN -1);
  35. current->name[SLEN -1] = '\0';
  36.  
  37. if (head == NULL)
  38. head = current;
  39. else
  40. prev->next = current;
  41.  
  42. prev = current;
  43. }
  44.  
  45. // display linked list
  46. current = head;
  47. while(current != NULL) {
  48. printf("No. = %d, Name = %s\n", current->no, current->name);
  49. current = current->next;
  50. }
  51.  
  52. // free linked list
  53. current = head;
  54. while(current != NULL) {
  55. prev = current;
  56. current = current->next;
  57. free(prev);
  58. }
  59. return 0;
  60. }
執行結果:
  1. 1
  2. ssss
  3. 2
  4. kkkk
  5. 3
  6. gggg
  7. 4
  8. llll
  9. 0
  10. No. = Name = No. = Name = No. = Name = No. = Name = No. = No. = 1, Name = ssss
  11. No. = 2, Name = kkkk
  12. No. = 3, Name = gggg
  13. No. = 4, Name = llll
好吧,我承認怪怪的,可以Work了!

For C++:
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class List {
  8. public:
  9. int no;
  10. string name;
  11. };
  12.  
  13. int main() {
  14. vector<list> vec;
  15.  
  16. while(1) {
  17. List list;
  18. cout << "No. = ";
  19. cin >> list.no;
  20.  
  21. if (list.no == 0)
  22. break;
  23.  
  24. cout << "Name = ";
  25. cin >> list.name;
  26.  
  27. vec.push_back(list);
  28. }
  29.  
  30. vector<list>::iterator iter = vec.begin();
  31. for(; iter != vec.end(); ++iter)
  32. cout << "No. = " << iter->no << ", Name = " << iter->name << endl;
  33. return 0;
  34. }

C++看起來簡單多了!

0 意見: