class Node {
@Override
public String toString() {
return "Node [pre=" + pre + ", obj=" + obj + ", next=" + next + "]";
}
private Node pre;
private Object obj;
private Node next;
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class LinkedList {
@Override
public String toString() {
return "MyLinkedList [first=" + first + ", last=" + last + "]";
}
private Node first;
private Node last;
public Node getFirst() {
return first;
}
public void setFirst(Node first) {
this.first = first;
}
public Node getLast() {
return last;
}
public void setLast(Node last) {
this.last = last;
}
/**
* 添加元素
*
* @param o
*/
public void add(Object o) {
if (first == null) {
Node n = new Node(); // 创建头节点
n.setObj(o);
n.setNext(null);
n.setPre(null);
first = n;
last = n;
} else { // 创建新节点
Node n = new Node();
n.setObj(o); // 将值赋给新节点
n.setPre(last); // 让该节点指向前一个节点
n.setNext(null); // 该节点的Next赋值为null
last.setNext(n); // 让上一个节点的Next指向该节点
last = n; // 将该节点设置为尾节点
}
}
/**
* 展示数据
*
* @param list
*/
public void show(LinkedList list) {
Node n = new Node();
n = list.getFirst();
if (n == null) {
return;
} else {
while (n != null) {
System.out.println(n.getObj());
n = n.getNext();
}
}
}
/**
* 删除指定元素
*
* @param list
* @param num
*/
public void delet(LinkedList list, Object num) {
Node n = new Node();
n = list.getFirst();
if (n == null)
return;
while (n != null) {
if (n.getObj().equals(num)) {
if (n.getPre() == null) {
n = n.getNext();
n.getPre().setNext(null);
n.setPre(null);
first = n;
return;
} else if (n.getNext() == null) {
n.getPre().setNext(null);
n.setPre(n);
} else {// if(n.getNext() != null){
n.getPre().setNext(n.getNext());
n.getNext().setPre(n.getPre());
}
}
n = n.getNext();
}
}
/**
* 设置元素
*
* @param list
* @param num
* @param o
*/
public void set(LinkedList list, Object num, Object o) {
Node n = new Node();
n = list.getFirst(); // 将新创建的节点指向头节点
if (n == null)
return;
while (n != null) { // 判断是否到尾节点
if (n.getObj().equals(num)) { // 找到要修改的元素
n.setObj(o); // 修改为指定元素
return;
}
n = n.getNext(); // 节点指针向下移动
}
}
/**
* 查找指定元素
*
* @param list
* @param o
* @return
*/
public int find(LinkedList list, Object o) {
int count = 1;
Node n = new Node();
n = list.getFirst();
if (n == null)
return -1;
while (n != null) {
if (n.getObj().equals(o)) {
return count;
}
n = n.getNext();
count++;
}
return -1;
}
public static void main(String[] args) {
// 新建自定义对象
LinkedList list = new LinkedList();
// 添加数据
list.add(66);
list.add(34);
list.add(33);
list.add(26);
list.add(88);
list.show(list);
System.out.println("=================");
list.delet(list, 66); // 删除指定元素
list.show(list);
}
}
自定义实现循环链表
最新推荐文章于 2023-10-15 19:18:49 发布