A picture to understand the insertion principle of LinkedList, understanding this can easily understand most of the content of the linked list.

First define a linked list class, and then implement

cut to the chase, post the picture

insert

Linked list

// An highlighted block
/**
 * 抽象一个链表中单个节点的类
 * @author wxl
 *
 */
public class Node {
    
    
	//节点中保存的数据
	private Object data;
	//指向下一个节点的地址
	private Node next;
	//构造器
	public Node() {
    
    }
	public Node(Object data, Node next) {
    
    
		super();
		this.data = data;
		this.next = next;
	}
	//get/ set方法
	public Object getData() {
    
    
		return data;
	}
	public void setData(Object data) {
    
    
		this.data = data;
	}
	public Node getNext() {
    
    
		return next;
	}
	public void setNext(Node next) {
    
    
		this.next = next;
	}
}

Linked list

public class LinkedList implements List{
    
    

	private Node head; //定义一个空头节点
	private int size; //用来记录数据结构的大小
	
	public LinkedList() {
    
    
		head = new Node(null,null);
	}
	@Override
	public void add(int index, Object obj) {
    
    
		//指定位置上添加
		if(index<0 || index >size) return;
		//使用临时变量,将head值赋予它
		Node curr = head;
		//找到index的位置,只能从头节点向后去遍历
		for(int i=0;i<index;i++) {
    
    
			curr = curr.getNext();
		}
		//准备一个新添加进来的节点
		Node node = new Node();
		node.setData(obj);
		node.setNext(curr.getNext());
		curr.setNext(node);
		size++;
		
	}
According to this figure and code, you can easily understand the insertion of the linked list.
Like it, like it and collect it!!!

Guess you like

Origin blog.csdn.net/xiaole060901/article/details/107884004