脚本宝典收集整理的这篇文章主要介绍了【145天】尚学堂高淇Java300集视频精华笔记(103-104),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
2集知识点
-
手写Linklist的常用方法:
add(Object obj)
add(int index,Object obj)
size()
get(int index)
rangCheck(int index)
remove(int index)
node(int index)
演示代码
package com.collection;
public class Node {
Node previous; //这里没加private是为了方便演示,应该加
Object obj; //这里没加private是为了方便演示,应该加 Node next; //这里没加private是为了方便演示,应该加
public void setPrevious(Node previous){
this.previous = previous;
}
public Object getPrevious(){
return previous;
}
public void setObj(Object obj){
this.obj = obj;
}
public Object getObj(){
return obj;
}
public void setNext(Node next){
this.next = next;
}
public Object getNext(){
return next;
}
}
package com.collection;
import java.util.List;
public class SxtLinkedList /*implements List*/ {
private Node first;
private Node last;
private int 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节点后增加新的节点
n.setPrevious(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n);
last = n;
}
size++;
}
public int size(){
return size;
}
public Object get(int index){
rangeCheck(index);
Node temp = node(index);
if(temp!=null){
return temp.obj;
}
return null;
}
public void rangeCheck(int index){
if(index<0||index>size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void remove(int index){
Node temp = node(index);
if(temp!=null){
Node up = temp.previous;
Node down = temp.next;
up.next = down;
down.previous = up;
size--;
}
}
public Node node(int index){
Node temp = null;
if(first!=null){
temp = first;
for(int i=0;i<index;i++){
temp = temp.next;
}
}
return temp;
}
public void add(int index,Object obj){
Node temp = node(2);
Node newNode = new Node();
newNode.obj = obj;
if(temp!=null){
Node up = temp.previous;
up.next = newNode;
newNode.previous = up;
temp.previous = newNode;
newNode.next = temp;
size++;
}
}
public static void main(String[] args){
SxtLinkedList list = new SxtLinkedList();
list.add("aaa");
list.add("bbb");
list.add(1,"BBB");
list.add("ccc");
System.out.println(list.size());
//list.remove(1);
System.out.println(list.get(1));
}
}
以上是脚本宝典为你收集整理的【145天】尚学堂高淇Java300集视频精华笔记(103-104)全部内容,希望文章能够帮你解决【145天】尚学堂高淇Java300集视频精华笔记(103-104)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。