简单的自己实现LinkedList的底层代码:
package testLinkedList;
/**
* 自己实现LinkedList底层代码
* @author *
*/
public class MyLinkedList {
private Node first; //头指针
private Node last; //尾指针
private int size;
public int size() {
return size;
}
public void add(Object obj) { //添加元素
Node n=new Node();
if(first==null) { //注意是指针为空而不是指针中的元素
n.setprevious(null);
n.setObj(obj);
n.setnext(null);
first=n;
last=n;
}else {
last.setnext(n);
n.setprevious(last);
n.setObj(obj);
n.setnext(null);
last=n;
}
size++;
}
public void insert(int index,Object obj) { //指定位置插入元素
Node nd=first;
if(index>size||index<0) { //判断是否越界
try {
throw new Exception();
}catch(Exception e){
e.printStackTrace(); //越界就抛出异常
}
}
if(first!=null) {
for(int i=0;i<index;i++) {
nd=nd.next;
}
if(nd!=null) {
Node n= new Node();
n.setObj(obj);
nd.next=n;
n.previous=nd;
n.next=nd.next;
nd.next.previous=n;
}
}
size++;
}
public Object get(int index) { //读取元素
Node nd=first;
if(index>size||index<0) { //判断是否越界
try {
throw new Exception();
}catch(Exception e){
e.printStackTrace(); //越界就抛出异常
}
}
if(first!=null) {
for(int i=0;i<index;i++) {
nd=nd.next;
}
}
return nd.obj;
}
public Object set(int index,Object obj) {
Node nd=first;
if(index>size||index<0) { //判断是否越界
try {
throw new Exception();
}catch(Exception e){
e.printStackTrace(); //越界就抛出异常
}
}
if(first!=null) {
for(int i=0;i<index;i++) {
nd=nd.next;
}
nd.obj=obj;
}
return nd.obj;
}
public void remove(int index) { //删除指定元素
Node nd=first;
if(index>size||index<0) { //判断是否越界
try {
throw new Exception();
}catch(Exception e){
e.printStackTrace(); //越界就抛出异常
}
}
if(first!=null) {
for(int i=0;i<index;i++) {
nd=nd.next;
}
nd.next.setprevious(nd.previous);
nd.previous.setnext(nd.next);
}
size--;
}
public static void main(String[] args) {
MyLinkedList mll=new MyLinkedList();
mll.add("aaa");
mll.add("bbb");
mll.add("ccc");
// mll.set(1, "ggg");
// mll.remove(1);
mll.insert(2, "hh");
System.out.println(mll.size);
System.out.println(mll.get(2));
}
}
package testLinkedList;
public class Node { //定义节点
Node previous; //头结点
Object obj; //结点内容
Node next; //下一结点
public Node() {
}
public Node(Node previous, Object obj, Node next) {
super();
this.previous = previous;
this.obj = obj;
this.next = next;
}
public Node getprevious() {
return previous;
}
public void setprevious(Node previous) {
this.previous = previous;
}
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;
}
}