前几天因为一个现场演示需要,现场实现手动实现了一个单链表,今天整理临时文件看到了这块代码,就简单整理了一下,发上来记录一下。
/**
* Created by leon.L on 2018/3/29.
* Desc : 模拟链表
*/
public class LinkedObj<T> {
private Node head;
private Node last;
private int size = 0;
class Node<T>{
T date;
Node next;
}
public LinkedObj() {}
public void add(T t) {
Node node = new Node();
node.date = t;
if (head == null) {
head = node;
} else if (last == null) {
last = node;
head.next = last;
} else {
Node temp = last;
temp.next = node;
last = node;
}
size ++;
}
public int size() {
return this.size;
}
/**
* 遍历链表
*/
public void each(){
iteritor(head);
}
private void iteritor(Node<T> node){
System.out.println(node.date);
if (node.next != null) {
iteritor(node.next);
}
}
/**
* 链表反转实现1:通过循环实现
*/
public void reverse(){
if (size < 2){
return;
}
Node preNode = head;
last = head;
Node currentNode = head.next;
head.next = null;
Node nextNode ;
while (currentNode != null) {
nextNode = currentNode.next;
currentNode.next = preNode;
preNode = currentNode;
currentNode = nextNode;
}
head = preNode;
}
/**
* 链表反转实现2:通过递归调用实现
*/
public void reverse2(){
doReverse(head, head.next);
Node t = head;
head = last;
last = t;
last.next = null;
}
private void doReverse(Node<T> preNode, Node<T> currentNode){
if (currentNode == null) {
return;
}
Node next = currentNode.next;
currentNode.next = preNode;
doReverse(currentNode, next);
}
public static void main(String[] abc){
LinkedObj<String> list = new LinkedObj<>();
list.add("11");
list.add("22");
list.add("33");
list.add("44");
list.add("55");
list.each();
list.reverse2();
list.each();
}
}