package linkede;
/**
* (带头)单链表
*
* @author codelmh
* @data 2021/12/9
*/
public class SingleLikedList<T> {
private Node head; //记录头结点
private Integer size = 0; // 链表大小
/**
* 链表反转
* @param singleLikedList
*/
public void reversalSingleLiked(SingleLikedList<T> singleLikedList){
Node head = singleLikedList.head;// head 指向头结点
Node pre = null;//存储头结点
Node next;// 下一个节点
//如果head !=null 继续走
while ( head != null) {
next = head.next;//下一个节点
head.next = pre; // 当前节点的next 指向 头结点
pre = head; // 头结点指向当前
head = next; // head 指向 下一个节点
}
singleLikedList.head = pre;
}
/**
* 清空链表
*/
public void clear(){
this.size = 0;
this.head = null;
}
/**
* 尾插法
* @param value
*/
public void addLast(T value){
Node node = new Node(value);
// 用一个临时节点记录 head
Node tail = head;
if ( this.head == null){
this.head = node;
}else{
// 获取尾部 这时 cur就是最后节点
while ( tail.next != null){
tail = tail.next;
}
tail.next = node;
}
size++;
}
/**
* 头插法
* @param value
*/
public void addFirst(T value) {
Node node = new Node(value);
// 如果 头结点为空,则链表为空
if (this.head == null)
this.head = node;
else{
node.next = this.head;
head = node;
}
this.size++;
}
/**
* 链表是否空
* @return
*/
public boolean isEmpty(){
return this.size == 0;
}
/**
* 链表大小
* @return
*/
public int size(){
return this.size;
}
private class Node {
T value; //数据
Node next; //指针
// 节点初始化
public Node(T value) {
this.next = null;
this.value = value;
}
}
}
本人小白一枚~ 若有错误请指正!