单向链表
/定义一个SingleLinkedList来管理数据
class SingleLinkedList{
private DataNode head = new DataNode();
public void add(DataNode node){
DataNode tmp = head;
while(true){
if(tmp.next == null){
tmp.next = node;
break;
}
tmp = tmp.next;
}
}
public boolean addAndOrder(DataNode node){
DataNode tmp = head;
while(true){
if(tmp.next == null){
tmp.next = node;
break;
}
if(node.num < tmp.next.num){
node.next = tmp.next;
tmp.next = node;
break;
}
if(tmp.next.num == node.num){
return false;
}
tmp = tmp.next;
}
return true;
}
public boolean update(DataNode node){
DataNode tmp = head;
while(true){
if(tmp.next == null){
return false;
}
if(tmp.next.num == node.num){
node.next = tmp.next.next;
tmp.next = node;
return true;
}
tmp = tmp.next;
}
}
public boolean delete(int num){
DataNode tmp = head;
while (true){
if(tmp.next == null){
return false;
}
if(tmp.next.num == num){
if(tmp.next.next == null){
tmp.next = null;
}else {
tmp.next = tmp.next.next;
}
return true;
}
tmp = tmp.next;
}
}
public void show(){
DataNode tmp = head;
while(true){
if(tmp.next == null){
break;
}
System.out.println(tmp.next);
tmp = tmp.next;
}
}
public int size(){
int num = 0;
DataNode tmp = head;
while (true){
if(tmp.next == null){
return num;
}
tmp = tmp.next;
num++;
}
}
public DataNode getByReciprocal(int order){
int size = size();
int num = size - order;
if(order <= 0 || order > size){
return null;
}
DataNode tmp = head.next;
while (true){
if(num == 0){
return tmp;
}
tmp = tmp.next;
num--;
}
}
public void reverse(){
if(size() <= 1){
return;
}
DataNode tmpHead = head.next.next;
DataNode tmp = head.next;
head.next = null;
while(true){
tmp.next = head.next;
head.next = tmp;
tmp = tmpHead;
tmpHead = tmp.next;;
if(tmpHead == null){
tmp.next = head.next;
head.next = tmp;
return;
}
}
}
public void reversePrint(){
if(head.next == null){
return;
}
Stack<DataNode> stack = new Stack<>();
DataNode tmp = head.next;
while(true){
if(tmp == null){
break;
}
stack.push(tmp);
tmp = tmp.next;
}
while (stack.size() > 0){
System.out.println(stack.pop());
}
}
}
class DataNode<T>{
public int num;
public T data;
public DataNode next;
public DataNode(int num,T data){
this.num = num;
this.data = data;
}
public DataNode(){}
@Override
public String toString() {
return "DataNode{" + "num=" + num + ", data=" + data.toString() + '}';
}
}