public class OneDirectLinkedList<T> {
private int size = 0;
//单向链表头结点
Node<T> head = new OneDirectLinkedList.Node(null);
//链表元素添加
public void add(T t) {
Node node = this.head;
while(node.next != null){
node = node.next;
}
node.next = new OneDirectLinkedList.Node(t);
size ++;
}
//链表反转
public void reverse() {
// Node next
Node<T> pre = head; //前一节点
Node<T> cur = head.next;//当前节点
Node<T> temp = null; //暂存后一个节点的引用
while (cur != null) {
//暂存后一个节点的引用
temp = cur.next;
//当前节点指针域指向前一个节点
cur.next = pre;
//pre指向下一个, cur指向下一个
pre = cur;
cur = temp;
};
//最后处理头结点
if(head.next != null){
head.next.next = null;
head.next = pre;
}
}
public String toString(){
StringBuffer re = new StringBuffer("[");
String spl = ", ";
Node<T> node = this.head.next;
while(node != null){
re.append(node.toString() + spl);
node = node.getNext();
};
if(this.head.next != null) {
return re.substring(0, re.length()-spl.length()) + "]";
} else{
return re + "]";
}
}
public int size() {
return this.size;
}
private static class Node<T> {
private T t;
private Node<T> next = null;
//构造方法
public Node(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
public String toString(){
return this.t.toString();
}
}
}
Java单链表实现——持续更新
最新推荐文章于 2022-06-24 22:05:14 发布