简易的链表

package employee;

import java.util.Objects;

/**
 * 自己写一个简易链表
 * @author 86188
 *
 * @param <E>
 */
public class SimpleList<E> {
	private Node head; //头节点
	private Node last; //尾节点
	public int size; //链表长度
	
	public SimpleList() {
		
	}
	public SimpleList(Node head, Node last, int size) {
		super();
		this.head = head;
		this.last = last;
		this.size = size;
	}

	
	//头部插入
	public void insertFirst(E e){
		Node<E> node = new Node<E>(e);
		//之前的头节点成为这个节点的下一个节点
		node.next = head;
		//这个节点成为新节点
		head = node;
		size++;
	}
	
	//读取
	public E get(E e){
		//获取头部元素
		Node<E> node = head;
		while(!Objects.isNull(node)) {
			//如果当前节点的数据和传入数据相等
			if(node.element.equals(e)) {
				return node.element;
			}
			node  = node.next;
		}
		return  null;
	}
	//删除指定的字符串
	public E earse(E e){
	
		E result = null;
		
		if(head.element.equals(e)) {
			result = (E) head.element;
			head = head.next;
			size--;
			return result;
		}else {
			Node<E> node = head;
			while(!Objects.isNull(node.next)) {
				
				if(node.next.element.equals(e)) {
					result = (E)node.next.element;
					node.next = node.next.next;
					size--;
					return result;
				}
				node  = node.next;
			}
		}
		return null;
		
	}
	//负责保存数据
	private  class Node<E> {
		Node previous;// 上一个节点
		Node next;// 下一个节点
		E element;// 数据
		public Node(Node previous, Node next, E element) {
			this.previous = previous;
			this.next = next;
			this.element = element;
		}
		public Node(E element) {
			this.element = element;
		}
		@Override
		public String toString() {
			return "Node [info="+element+",next="+next+"]";
		}
	}
	 @Override
	    public String toString() {
		// 打印head节点会因为next打印出整个链表的内容
	        return "SimpleList [node=" + head + "]";
	    }
	
}

  

package employee;

public class TestSimpleList {

	public static void main(String[] args) {
		SimpleList<String>  simpleList = new SimpleList<String>();
		simpleList.insertFirst("newStart1");
		simpleList.insertFirst("newStart2");
		simpleList.insertFirst("newStart3");
		simpleList.insertFirst("newStart4");
		System.out.println(simpleList.get("newStart4"));
		simpleList.earse("newStart2");
		System.out.println(simpleList.toString()+simpleList.size);

	}

}

  

posted @ 2020-06-03 18:59  宥晔  阅读(166)  评论(0编辑  收藏  举报