Advertisement
gabuwu

TP04-EJ4-G3.3-SimpleLinkedList

Oct 27th, 2021
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. package TP4;
  2.  
  3.  
  4. import java.util.Iterator;
  5.  
  6. public class SimpleLinkedList<ELEMENT> implements ILinkedList<ELEMENT> {
  7.  
  8. //region Node Class
  9.  
  10. private class Node<ELEMENT> {
  11. public ELEMENT item;
  12. public Node<ELEMENT> next;
  13.  
  14. public Node() {
  15. this(null, null);
  16. }
  17. public Node(ELEMENT item) {
  18. this(item, null);
  19. }
  20. public Node(ELEMENT item, Node<ELEMENT> next) {
  21. this.item = item;
  22. this.next = next;
  23. }
  24.  
  25. @Override
  26. public String toString() {
  27. return this.item.toString();
  28. }
  29. }
  30. //endregion
  31.  
  32. //region Attributes
  33.  
  34. protected Node<ELEMENT> head;
  35. protected int count;
  36. protected Node<ELEMENT> tail;
  37. //endregion
  38.  
  39. //region Constructors
  40.  
  41. public SimpleLinkedList() {
  42. this.head = null;
  43. this.count = 0;
  44. this.tail = null;
  45. }
  46. //endregion
  47.  
  48. //region Linked List Methods
  49.  
  50. // Returns the number of elements in this list.
  51. public int size() {
  52. return this.count;
  53. }
  54.  
  55.  
  56. // Appends the specified element to the end of this list.
  57. public void addLast(ELEMENT item) {
  58. Node<ELEMENT> temp = new Node<ELEMENT>(item, null);
  59. if (this.count == 0) {
  60. this.head = temp;
  61. } else {
  62. this.tail.next = temp;
  63. }
  64. this.tail = temp;
  65. ++this.count;
  66. }
  67.  
  68.  
  69. //region Object Methods
  70.  
  71. @Override
  72. public String toString() {
  73.  
  74. if (this.size() <=0) {
  75. return "";
  76. }
  77.  
  78. // from https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/StringBuilder.html
  79. StringBuilder sb = new StringBuilder();
  80.  
  81. sb.append("[" + this.head.item.toString());
  82. for (Node<ELEMENT> skip = this.head.next; skip != null; skip = skip.next) {
  83. sb.append(" " + skip.item.toString());
  84. }
  85. sb.append("]");
  86.  
  87. return sb.toString();
  88. }
  89.  
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement