
package Linked;
public class Mylinked {
private Node first;//链表的第一个节点
private Node last;//链表的最后一个节点
private int size = 0;//节点的数量
public Node search(Object ele) {
Node current = this.first;
for (int i = 0; i < size; i++) {
if (!current.ele.equals(ele)) {
if (current.next == null) {
return null;
}
current=current.next;
}
}
return current;
}
public void remove(Object ele) {
//找到被删除的节点
Node current = this.first;
for (int i = 0; i < size; i++) {
if (!current.ele.equals(ele)) {
if (current.next == null) {
return;
}
current=current.next;
}
}
//删除节点
if(current==first){
this.first=current.next;
this.first.prev=null;
}else if(current==last){
this.last=current.prev;
this.last.next=null;
}else{
//把删除当前节点下一个节点作为删除节点上一个节点的下一个节点
current.prev.next=current.next;
//把删除节点的上一个节点作为删除节点的下一个节点的上一个节点
current.next.prev=current.next;
}
size--;
}
public void addFirst(Object ele) {
Node node = new Node(ele);//需要保存的节点对象
if (size == 0) {//当链表中没有节点的时候
this.first = node;
this.last = node;
} else {
node.next = this.first;//把之前的第一个节点作为新增的第一个节点的下一个节点
this.first.prev = node;//把新增节点作为第一个节点的上一个节点
this.last = node;//把新增节点作为第一个节点
}
size++;
}
public void addLast(Object ele) {//在最后一个节点插入数据
Node node = new Node(ele);//需要保存的节点对象
if (size == 0) {//当链表中没有节点的时候
this.first = node;
this.last = node;
} else {
this.last.next = node;//把新增的节点作为最后一个的下一个节点
node.prev = this.last;//把之前最后一个节点作为新增节点的上一个节点
this.last = node;//把新增的节点作为最后一个节点
}
size++;
}
public String toString() {//覆盖父类中的方法
if (size == 0) {
return "[ ]";
}
StringBuffer sb = new StringBuffer(size * 2 + 1);
Node current = this.first;//第一个节点
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(current.ele);
if (i != size - 1) {
sb.append(",");
} else {
sb.append("]");
}
current = current.next;//获取自己的下一个节点
}
return sb.toString();
}
class Node {
Node prev;//上一个节点对象
Node next;//下一个节点对象
Object ele;//当前节点中存储的数据
public Node(Object ele) {
this.ele = ele;
}
}
}
package Linked;
public class MylinkedDemo {
public static void main(String[] args) {
Mylinked list=new Mylinked();
list.addFirst("a");
list.addLast("b");
list.addLast("c");
list.addLast("d");
list.addLast("e");
System.out.println(list);
list.remove("c");
System.out.println(list);
}
}
