ZenScript main repository
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LinkedList.zs 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. export class LinkedList<T> {
  2. var first as Node?;
  3. var last as Node?;
  4. var size as int : get;
  5. public get empty as bool
  6. => first == null;
  7. public add(value as T) as void {
  8. if first == null {
  9. first = last = new Node(value);
  10. } else {
  11. val node = new Node(value);
  12. last.next = node;
  13. node.prev = last;
  14. last = node;
  15. }
  16. size++;
  17. }
  18. public clear() as void {
  19. first = last = null;
  20. size = 0;
  21. }
  22. public [](index as int) as T {
  23. var node = first;
  24. while index > 0 {
  25. if node == null
  26. return panic<T>("index out of bounds");
  27. node = node.next;
  28. }
  29. if node == null
  30. return panic<T>("index out of bounds");
  31. return node.value;
  32. }
  33. public implements Queue<T> {
  34. poll() as T {
  35. if first == null
  36. return panic<T>("Cannot poll an empty queue");
  37. val result = first.value;
  38. first = first.next;
  39. if first == null
  40. last = null;
  41. else
  42. first.prev = null;
  43. size--;
  44. }
  45. peek() as T? {
  46. return first.value;
  47. }
  48. offer(value as T) as void
  49. => add(value);
  50. }
  51. private struct Node {
  52. var next as Node?;
  53. var prev as Node?;
  54. val value as T;
  55. this(value as T) {
  56. this.value = value;
  57. }
  58. }
  59. }