Add the Compactable interface.
[TP_POO.git] / Structure / Liste.java
1
2
3 public class Liste extends Structure {
4
5 private class IntNode {
6 private int data;
7 private IntNode next;
8
9 IntNode(int value) {
10 setData(value);
11 setNext(null);
12 }
13
14 IntNode(int value, IntNode nextNode) {
15 setData(value);
16 setNext(nextNode);
17 }
18
19 public int getData() {
20 return data;
21 }
22
23 public void setData(int value) {
24 data = value;
25 }
26
27 public IntNode getNext() {
28 return next;
29 }
30
31 public void setNext(IntNode nextNode) {
32 next = nextNode;
33 }
34
35 }
36
37 private IntNode headNode;
38 private int list_counter;
39
40 Liste() {
41 setHeadNode(null);
42 setSize(0);
43 }
44
45 private boolean isEmpty()
46 {
47 return getHeadNode() == null;
48 }
49
50 public int getSize() {
51 return list_counter;
52 }
53
54 public void setSize(int size) {
55 list_counter = size;
56 }
57
58 public void setHeadNode(IntNode node) {
59 headNode = node;
60 }
61
62 public IntNode getHeadNode() {
63 return headNode;
64 }
65
66 public boolean inserer(int value) {
67 boolean found = false;
68 if (isEmpty()) {
69 headNode = new IntNode(value);
70 list_counter++;
71 return true;
72 } else if (value == headNode.getData()) {
73 found = true;
74 return true;
75 } else {
76 IntNode nodeCursorNext = headNode.getNext();
77 while (nodeCursorNext != null) {
78 if (value == nodeCursorNext.getData()) {
79 found = true;
80 break;
81 } else {
82 nodeCursorNext = nodeCursorNext.getNext();
83 }
84 }
85 if (!found) {
86 headNode = new IntNode(value, headNode);
87 list_counter++;
88 }
89 // Insertion in a linked list can't fail
90 return true;
91 }
92 }
93
94 public boolean supprimer(int value) {
95 boolean deleted = false;
96 if (isEmpty()) {
97 return deleted;
98 } else if (value == headNode.getData()) {
99 headNode = headNode.getNext();
100 deleted = true;
101 list_counter--;
102 } else {
103 IntNode nodeCursor = headNode;
104 IntNode nodeCursorNext = headNode.getNext();
105 while (nodeCursorNext != null) {
106 if (value == nodeCursorNext.getData()) {
107 nodeCursor.setNext(nodeCursorNext.getNext());
108 deleted = true;
109 list_counter--;
110 break;
111 } else {
112 nodeCursor = nodeCursorNext;
113 nodeCursorNext = nodeCursorNext.getNext();
114 }
115 }
116 }
117 return deleted;
118 }
119
120 public void afficher() {
121 String className = this.getClass().getSimpleName();
122 int i = 0;
123 System.out.println("---- " + className + " ----");
124 if (isEmpty()) {
125 return;
126 } else if (headNode.getNext() == null) {
127 System.out.println("element " + i + " : " + headNode.getData());
128 } else {
129 IntNode nodeCursorNext = headNode.getNext();
130 System.out.println("element " + i + " : " + headNode.getData());
131 i++;
132 while (nodeCursorNext != null) {
133 System.out.println("element " + i + " : " + nodeCursorNext.getData());
134 nodeCursorNext = nodeCursorNext.getNext();
135 i++;
136 }
137 }
138 }
139
140 }