linked_list.carbon 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. //
  5. // NOAUTOUPDATE
  6. package ExplorerTest api;
  7. class ListElement{
  8. fn Create(value: i32)->ListElement{
  9. return {
  10. .element = Optional(i32).Create(value),
  11. .next = Optional(ListElement*).CreateEmpty()
  12. };
  13. }
  14. fn set[addr self: Self*] (value: Optional(ListElement*)){
  15. (*self).next = value;
  16. }
  17. var element: Optional(i32);
  18. var next: Optional(ListElement*);
  19. }
  20. class List{
  21. fn Create() -> List{
  22. return {.next = Optional(ListElement*).CreateEmpty() };
  23. }
  24. fn insert[addr self: Self*] (value: i32){
  25. if( not (*self).next.HasValue() ){
  26. (*self).next = Optional(ListElement*).Create( heap.New(ListElement.Create(value)) );
  27. return;
  28. }
  29. var iter: Optional(ListElement*) = (*self).next;
  30. var node: auto = (iter.Get());
  31. while((*node).next.HasValue()){
  32. iter = (*node).next;
  33. node = (iter.Get());
  34. }
  35. var v : ListElement* = iter.Get();
  36. var x: Optional(ListElement*) = Optional(ListElement*).Create( heap.New(ListElement.Create(value) ));
  37. (*v).set(x);
  38. }
  39. fn print[self: Self] (){
  40. var iter: Optional(ListElement*) = self.next;
  41. while(iter.HasValue()){
  42. var node: auto = *(iter.Get());
  43. Print("{0}",node.element.Get());
  44. var node_ptr: auto = iter.Get();
  45. iter = node.next;
  46. }
  47. }
  48. fn clean[addr self: Self*] (){
  49. var head: auto = (*self).next;
  50. while(head.HasValue()){
  51. var tmp: auto = head;
  52. head = (*head.Get()).next;
  53. heap.Delete(tmp.Get());
  54. }
  55. (*self).next= Optional(ListElement*).CreateEmpty();
  56. }
  57. var next: Optional(ListElement*);
  58. }
  59. fn Main() -> i32{
  60. var list: List = List.Create();
  61. list.insert(1);
  62. list.insert(2);
  63. list.insert(3);
  64. list.insert(4);
  65. list.print();
  66. list.clean();
  67. list.print();
  68. list.insert(1);
  69. list.insert(2);
  70. list.insert(3);
  71. list.insert(4);
  72. list.print();
  73. return 0;
  74. }
  75. // CHECK:STDOUT: 1
  76. // CHECK:STDOUT: 2
  77. // CHECK:STDOUT: 3
  78. // CHECK:STDOUT: 4
  79. // CHECK:STDOUT: 1
  80. // CHECK:STDOUT: 2
  81. // CHECK:STDOUT: 3
  82. // CHECK:STDOUT: 4
  83. // CHECK:STDOUT: result: 0