Some functions of LinkedList handwritten source code
Today, the epidemic is getting better. The moon is around 15 years old. Remember to watch the moon at night
If you have problems with your rough opinions, you can point out how much progress you can make at any time
The bottom layer of LinkedList is linked list structure
First of all, we need to understand what is the chain list structure, as shown in the figure below

Basically, the above figure means that each node code can:
public class Node {
private Node previous;
private Node next;
private Object element;
public Node(Object element) {
this.element = element;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getElement() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
}
This is a handwritten part of the source code, which can be written by yourself
Relatively simple function
public class MyLinkedList {
private Node first;
private Node end;
private int size;
public void add(Object obj){
Node node = new Node(obj);
if(first == null){
first =node;
end =node;
}else{
node.setPrevious(end);
node.setNext(null);
end.setNext(node);
end = node;
}
size++;
}
public void add(int index,Object obj){
Node node = getNode(index);
Node newNode = new Node(obj);
if(node != null){
Node up = node.getPrevious();
if(up !=null){
up.setNext(newNode);
}
node.setPrevious(newNode);
newNode.setNext(node);
if(index ==0){
first.setPrevious(newNode);
newNode.setNext(first);
first =newNode;
}
if(index == size-1){
end = newNode;
}
size++;
}
}
public Object get(int index){
Node temp = null;
return temp.getElement();
}
public Node getNode(int index){
Node temp = null;
if(index<0 || index>size-1){
throw new RuntimeException("Subscript boundary crossing"+index);
}
if(index<size>>1){
temp =first;
for (int i = 0; i <index; i++) {
temp = temp.getNext();
}
}else{
temp =end;
for (int i = size-1; i>index; i--) {
temp = temp.getPrevious();
}
}
return temp;
}
public void remove(int index){
Node node = getNode(index);
if(node != null) {
Node up = node.getPrevious();
Node down = node.getNext();
if (up != null) {
up.setNext(down);
}
if (down != null) {
down.setPrevious(up);
}
if (index == 0) {
first = down;
}
if (index == size - 1) {
end = up;
}
}
}
@Override
public String toString() {
Node temp = first;
StringBuilder strb = new StringBuilder("[");
while (temp!=null){
strb.append(temp.getElement()+",");
temp =temp.getNext();
}
strb.setCharAt(strb.length()-1,']');
return strb.toString();
}
}```
89 original articles published, 47 praised, 10000 visitors+
Posted by EricS on Sun, 09 Feb 2020 06:13:15 -0800