java 用双向链表实现SJBLinkedList

本文介绍了一个简单的双向链表实现,包括添加、获取和删除元素等基本操作。通过具体的Java代码示例展示了如何手动构建和维护双向链表的数据结构。

 

public class SJBLinkedList{

 

private Node first;

 

private Node last;

 

private int size;

 

public int size(){

return size;

}

 

public boolean isEmpty(){

return size == 0;

}

 

public void add(Object obj){

 

Node node = new Node();

 

if(first == null){

 

node.obj = obj;

node.previous = null;

node.next = null;

 

first = node;

last = node;

 

}else{

 

node.obj = obj;

node.previous = last;

node.next = null;

 

last.next = node;

last = node;

 

}

 

size++;

 

}

 

 

private Node getNode(int index){

 

if(index < 0 || index >size ){

try {

throw new Exception();

} catch (Exception e) {

 

e.printStackTrace();

System.exit(0);

}

}

 

Node temp = null;

 

if(first != null){

temp = first;

for (int i=0;i<index;i++){

temp = temp.next;

}

}

 

return temp; 

 

}

 

 

public Object get(int index){

return getNode(index).obj;

}

 

public void remove(int index){

 

if(index < 0 || index >size ){

try {

throw new Exception();

} catch (Exception e) {

 

e.printStackTrace();

System.exit(0);

}

}

 

Node currentNode = getNode(index);

Node upNode = currentNode.previous;

Node downNode = currentNode.next;

 

upNode.next = downNode;

downNode.previous = upNode;

 

size--;

 

}

 

 

private class Node{

 

private Node previous;

 

private Object obj;

 

private Node next;

 

public Node(Node previous,Node next,Object obj){

this.previous = previous;

this.obj = obj;

this.next = next;

}

 

public Node(){

 

}

 

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;

}

 

 

}

 

 

 

public static void main(String[] args){

 

SJBLinkedList list = new SJBLinkedList();

list.add("123");

list.add("234");

list.add("345");

 

for(int i=0;i<3;i++){

System.out.println(list.get(i));

}

 

//System.out.println(list.get(5));

 

}

 

 

}

转载于:https://www.cnblogs.com/jianbo-su/p/5870708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值