一图理解LinkedList的插入原理,理解这个就可以轻松理解链表的大部分内容哦

先定义一个链表的类,然后实现

废话不多说,上图

插入

链表类

// 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;
	}
}

链表类

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++;
		
	}
根据这个图和代码就可以轻松理解链表的插入.
喜欢就点赞收藏走起喽!!!

猜你喜欢

转载自blog.csdn.net/xiaole060901/article/details/107884004