有序链表实现
代码实现
public class SortedLinkedList {
private Node first;
public SortedLinkedList() {
this.first = null;
}
public void insert(int data){
Node newNode = new Node(data);
Node previous = null;
Node current = first;
while (current !=null && data > current.data){
previous = current;
current = current.next;
}
//只有一个
if (previous == null){
first = newNode;
}else {
previous.next = newNode;
}
newNode.next = current;
}
public Node find(int data){
Node current = first;
while (current.data != data){
if (current.next == null){
return null;
}else {
current = current.next;
}
}
return current;
}
public Node delete(int data){
Node current = first;
Node previous = first;
current = find(data);
if (current != null){
if (current == first){
first = first.next;
}else {
previous.next = current.next;
}
}
return current;
}
class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
'}';
}
}
public void disPlay(){
Node temp = first;
while (temp != null){
System.out.println(temp.data);
temp = temp.next;
}
}
}
网友评论