public class ListNodeDemo {
public static void main(String[] args) {
ListLinkedList linkedList = new ListLinkedList();
linkedList.addNode(1);
linkedList.addNode(3);
linkedList.addNode(9);
System.out.println("头插法插入节点:");
linkedList.printList();
System.out.println("-----------------------");
//linkedList.deleteFirst();
//System.out.println("删除第一个元素");
//linkedList.printList();
Object obj = linkedList.findNode(3);
System.out.printf("查找值为%d的节点:%d\n", 3, obj);
System.out.println("删除指定值的节点:");
linkedList.removeNode(3);
linkedList.printList();
System.out.println("尾部插入元素:");
linkedList.addNodeTwo(1111);
linkedList.printList();
}
}
class ListLinkedList {
/* 构建空的链表,即头节点 */
ListNode listNode = new ListNode();
ListNode head = listNode.head;
/**
* 判断链表是否为空
*
* @return
*/
public boolean isEmpty() {
return head == null;
}
/**
* 添加结点(头插法)
*
* @param data
*/
public void addNode(Object data) {
ListNode node = new ListNode(data);
node.next = head;
head = node;
}
/**
* 添加节点(尾部添加)
* @param data
*/
public void addNodeTwo(Object data) {
ListNode temp = head;
ListNode node = new ListNode(data);
//链表还未有节点时
if (temp.next == null) {
node.next = head;
} else {
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
}
/**
* 删除结点(从头部删除)
*/
public void deleteFirst() {
if (head == null) {
System.out.println("链表为空,无法删除!");
return;
}
ListNode temp = head;
head = head.next;
}
/**
* 查找指定值的节点,并返回
*
* @param obj
* @return
*/
public Object findNode(Object obj) {
if (head == null) {
try {
throw new Exception("链表为空!");
} catch (Exception e) {
e.printStackTrace();
}
}
ListNode cur = head;
while (cur != null) {
if (cur.value == obj) {
return cur.value;
}
cur = cur.next;
}
return null;
}
/**
* 移除指定值的节点
*
* @param obj
*/
public void removeNode(Object obj) {
if (isEmpty()) {
System.out.println("链表为空!");
return;
}
if (head.value == obj) {
head = head.next;
} else {
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
if (cur.value == obj) {
pre.next = cur.next;
}
pre = cur;
cur = cur.next;
}
}
}
/**
* 打印链表信息
*/
public void printList() {
if (head.next == null) {
System.out.println("链表为空!");
return;
}
ListNode temp = head;
while (temp.next != null) {
System.out.print(temp.value + "->");
temp = temp.next;
}
System.out.println(temp.value);
}
}
/**
* 定义链表的数据结构
*/
class ListNode {
public ListNode next = null;
public Object value;
public ListNode head = null;
public ListNode() {
this.value = null;
this.value = null;
}
public ListNode(Object x) {
this.value = x;
this.next = null;
}
}
运行结果:
头插法插入节点:
9->3->1
-----------------------
查找值为3的节点:3
删除指定值的节点:
9->1
尾部插入元素:
9->1->1111