作者:好人好报 | 来源:互联网 | 2024-10-29 11:03
本文介绍了实现链表数据结构的方法与技巧,通过定义一个`MyLinkedList`类来管理链表节点。该类包含三个主要属性:`first`用于指向链表的第一个节点,`last`用于指向链表的最后一个节点,以及`size`用于记录链表中节点的数量。此外,还详细探讨了如何通过这些属性高效地进行链表的操作,如插入、删除和查找等。
public class MyLinkedList {
public LinkedNode first;
public LinkedNode last;
public int size;
public void add(Object obj) {
LinkedNode n = new LinkedNode();
if (first == null) {
n.setPrevious(null);
n.setObj(obj);
n.setNext(null);
first = n;
last = n;
} else {
n.setPrevious(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n);
last = n;
}
size++;
}
public int size() {
return size;
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: " + index + ", Size: " + size;
}
public Object get(int i) {
// 考虑越界
LinkedNode node = getNode(i);
if(node!=null){
return node.getObj();
}
return null;
}
public LinkedNode getNode(int i){
rangeCheck(i);
LinkedNode temp = null;
if (first != null) {
temp = first;
for (int j = 0; j temp = temp.getNext();
}
}
return temp;
}
public void delete(int i) {
if(null!=getNode(i)){
LinkedNode temp = getNode(i);
LinkedNode pre = temp.getPrevious();
LinkedNode next = temp.getNext();
pre.setNext(next);
next.setPrevious(pre);
size--;
}
}
public void add(int i,Object obj) {
LinkedNode n = new LinkedNode();
if(first==null && i==0 && size==0){
n.setPrevious(null);
n.setObj(obj);
n.setNext(null);
first = n;
last = n;
} else{
if(null!=getNode(i)){
LinkedNode temp = getNode(i);
LinkedNode pre = temp.getPrevious();
LinkedNode next = temp.getNext();
n.setObj(obj);
if(pre==null){
first = temp;
n.setPrevious(first);
first.setNext(n);
}
n.setPrevious(pre);
pre.setNext(n);
if(next==null){//如果找不到最后一个就是最后一个
last = temp;
n.setNext(last);
last.setPrevious(n);
}else{
n.setNext(next);
next.setPrevious(n);
}
}
}
size++;
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.delete(1);
list.add(1, "ddd");
System.out.println(list.get(1));
}
}
?
public class LinkedNode {
private LinkedNode previous;
private Object obj;
private LinkedNode next;
public LinkedNode getPrevious() {
return previous;
}
public void setPrevious(LinkedNode previous) {
this.previous = previous;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public LinkedNode getNext() {
return next;
}
public void setNext(LinkedNode next) {
this.next = next;
}
}
?