linked_list.carbon 2.2 KB

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