您的位置:首页 > 其它

集合第二步: 模拟LinkedList底层实现

2017-08-21 14:33 495 查看
package cn.sdut.chapter5;

/*
* LinkedList 底层是一个双向链表   模拟实现
*/
public class MyLinkedList {

private int size = 0;
private node head;
private node last;

class node {
node pre;
node next;
String data;

node(String data) {
this.data = data;
}

}

// 添加
public void add(String str) {
node node = new node(str);
if (size == 0) {
this.head = node;
this.last = node;
} else {
this.last.next = node;
node.pre = this.last;
this.last = node;
}
size++;

}

public void print() {
node current = this.head;
while (current != null) {
System.out.println(current.data);
current = current.next;
}

}

//删除
public void remove(String str) {
node current = this.head;
while (current != null) {
if (current.data.equals(str)) {
if (current == this.head) {
this.head = current.next;
this.head.pre = null;
} else if (current == this.last) {
this.last = current.pre;
this.last.next = null;
} else {
current.next.pre = current.pre;
current.pre.next = current.next;
}
size--;
break;
} else {
current = current.next;
}

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: