1.初始化节点
package linkedlist;
public class BookNode {
public int id;
public String name;
public double price;
public BookNode pre;
public BookNode next;
@Override
public String toString() {
return "BookNode{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
public BookNode(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
}
2.初始化链表及简单操作
package linkedlist;
import jdk.nashorn.internal.ir.IfNode;
public class LinkedList {
// 头结点
BookNode node = new BookNode(0, "", 0.0);
/**
* 在链表尾添加新的节点
*/
public void add(BookNode bookNode) {
BookNode temp = node;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = bookNode;
bookNode.pre = temp;
}
/**
* 修改节点
*/
public void update(BookNode bookNode) {
// 判断非空
if (node.next == null) {
System.out.println("此链表为空");
return;
}
boolean flag = false;
BookNode temp = node;
while (true) {
if (temp.id == bookNode.id) {
break;
}
if (temp == null) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
System.out.println("链表中没有该节点");
} else {
temp.name = bookNode.name;
temp.price = bookNode.price;
}
}
/**
* 根据id删除元素
*
* @param id
*/
public void del(int id) {
// 判断非空
if (node.next == null) {
System.out.println("此链表为空");
}
boolean flag = false;
BookNode temp = node;
while (true) {
if (temp.id == id) {
break;
}
if (temp.next == null) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
System.out.println("链表中没有此元素");
} else {
temp.pre.next = temp.next;
if (temp.next != null) {
temp.next.pre = temp.pre;
}
}
}
/**
* 遍历元素
*/
public void list() {
// 判断非空
if (node.next == null) {
System.out.println("此链表为空");
return;
}
BookNode temp = node.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
3.简单测试
package linkedlist;
public class LinkedListTest {
public static void main(String[] args) {
LinkedList list = new LinkedList();
BookNode bookNode1 = new BookNode(1, "a", 66);
BookNode bookNode2 = new BookNode(2, "b", 66);
BookNode bookNode3 = new BookNode(3, "c", 66);
BookNode bookNode4 = new BookNode(4, "d", 66);
list.list();
// 添加
list.add(bookNode1);
list.add(bookNode2);
list.add(bookNode3);
list.add(bookNode4);
//list.list();
// 删除
list.del(1);
list.list();
// 修改
list.update(new BookNode(2, "aaa", 666666));
list.list();
}
}
|