linked_list.carbon 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // AUTOUPDATE
  6. // RUN: %{explorer-run}
  7. // RUN: %{explorer-run-trace}
  8. // CHECK:STDOUT: 1
  9. // CHECK:STDOUT: 2
  10. // CHECK:STDOUT: 3
  11. // CHECK:STDOUT: 4
  12. // CHECK:STDOUT: 1
  13. // CHECK:STDOUT: 2
  14. // CHECK:STDOUT: 3
  15. // CHECK:STDOUT: 4
  16. // CHECK:STDOUT: result: 0
  17. package ExplorerTest api;
  18. class ListElement{
  19. fn Create(value: i32)->ListElement{
  20. return {
  21. .element = Optional(i32).Create(value),
  22. .next = Optional(ListElement*).CreateEmpty()
  23. };
  24. }
  25. fn set[addr self: Self*] (value: Optional(ListElement*)){
  26. (*self).next = value;
  27. }
  28. var element: Optional(i32);
  29. var next: Optional(ListElement*);
  30. }
  31. class List{
  32. fn Create() -> List{
  33. return {.next = Optional(ListElement*).CreateEmpty() };
  34. }
  35. fn insert[addr self: Self*] (value: i32){
  36. if( not (*self).next.HasValue() ){
  37. (*self).next = Optional(ListElement*).Create( heap.New(ListElement.Create(value)) );
  38. return;
  39. }
  40. var iter: Optional(ListElement*) = (*self).next;
  41. var node: auto = (iter.Get());
  42. while((*node).next.HasValue()){
  43. iter = (*node).next;
  44. node = (iter.Get());
  45. }
  46. var v : ListElement* = iter.Get();
  47. var x: Optional(ListElement*) = Optional(ListElement*).Create( heap.New(ListElement.Create(value) ));
  48. (*v).set(x);
  49. }
  50. fn print[self: Self] (){
  51. var iter: Optional(ListElement*) = self.next;
  52. while(iter.HasValue()){
  53. var node: auto = *(iter.Get());
  54. Print("{0}",node.element.Get());
  55. var node_ptr: auto = iter.Get();
  56. iter = node.next;
  57. }
  58. }
  59. fn clean[addr self: Self*] (){
  60. var head: auto = (*self).next;
  61. while(head.HasValue()){
  62. var tmp: auto = head;
  63. head = (*head.Get()).next;
  64. heap.Delete(tmp.Get());
  65. }
  66. (*self).next= Optional(ListElement*).CreateEmpty();
  67. }
  68. var next: Optional(ListElement*);
  69. }
  70. fn Main() -> i32{
  71. var list: List = List.Create();
  72. list.insert(1);
  73. list.insert(2);
  74. list.insert(3);
  75. list.insert(4);
  76. list.print();
  77. list.clean();
  78. list.print();
  79. list.insert(1);
  80. list.insert(2);
  81. list.insert(3);
  82. list.insert(4);
  83. list.print();
  84. return 0;
  85. }