public class SingleLinkedList {
private int length; //链表节点的个数
private Node head; //链表的头节点
public SingleLinkedList() {
length = 0;
head = null;
}
// 链表的每个节点的数据结构描述类
private class Node {
private Object data; //每个节点的数据
private Node next; //下一个节点的连接
public Node(Object data) {
this.data = data;
}
}
//在链表的头部添加元素
public Object addHead(Object obj) {
Node newHead = new Node(obj); //1:定义1个新节点
if(length == 0) {//2:如果链表为空,则该将节点设置为头节点
head = newHead;
} else {//3:设置当前插入的节点为头节点,并将其下一个节点指向原来的头节点
newHead.next = head;
head = newHead;
}
length++;// 4:链表的长度+1
return obj;
}
//删除指定的元素,若删除成功则返回true
public boolean delete(Object value) {
if (length == 0) {
return false;
}
Node current = head;
Node previous = head;
while (current.data != value) {
if(current.next == null) {
return false;
}else {
previous = current;
current = current.next;
}
}
//如果删除的节点是头节点
if(current == head) {
head = current.next;
length--;
}else {//删除的节点不是头节点
previous.next = current.next;
length--;
}
return true;
}
//查找指定的元素,如果找到了,则返回节点Node;如果找不到,则返回null
public Node find(Object obj) {
Node current = head;
int tempSize = length;
while (tempSize > 0) {
if (obj.equals(current.data)) {
return current;
} else {
current = current.next;
}
tempSize--;
}
return null;
}
//测试主方法
public static void main(String[] args) {
String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
SingleLinkedList singleLinkedList = new SingleLinkedList();
for(String letter : letters) {
singleLinkedList.addHead(letter);
}
singleLinkedList.delete("W");
System.out.println(singleLinkedList.toString());
Node u = singleLinkedList.find("U");
System.out.println(u);
}
}
单向链表Java实现
最新推荐文章于 2024-10-01 09:29:45 发布