오름차순정렬된 값을 유지하는 연결리스트의 구현
public class LinkedList {
private Node start;
public void insert(int x) {
if(start == null || start.data > x) {
start = new Node(x, start);
return;
}
Node p = start;
while(p.next != null) {
if(p.next.data > x) break;
p = p.next;
}
p.next = new Node(x, p.next);
}
public void delete(int x) {
if(start == null || start.data > x) // x is not in the list
return;
if(start.data == x) // x is the first element in the list
start = start.next;
for(Node p = start; p.next != null; p = p.next) {
if(p.next.data > x) break; // x is not in the list
if(p.next.data == x) { // x is in the p.next node
p.next = p.next.next; // delete it
break;
}
}
}
private class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
// print
public void print() {
for(Node p = start; p != null; p = p.next) {
System.out.println(p.data);
}
}
public static void main(String [] args) {
LinkedList list = new LinkedList();
list.insert(5);
list.insert(15);
list.delete(5); //delete
list.insert(23);
list.insert(58);
list.print();
}
}
TAG연결리스트의 구현