0
点赞
收藏
分享

微信扫一扫

手写单双向链表

手写双向链表

双向链表类(BidirectionalLinkedList)

public class BidirectionalLinkedList<E> {
	
	//元素个数
    transient int size = 0;//0
   	//第一个节点
    transient Node<E> first;//null
    //最后一个节点
    transient Node<E> last;//null
    
    //添加类
    public void add(E e){
    	 //final Node<E> l = last;
         final Node<E> newNode = new Node<>(last, e, null);
         if (first == null)
             first = newNode;
         else
             last.next = newNode;
         last = newNode;
    }
    
    //正序打印类
    public void positiveOrderPrint(){
    	Node<E> node = first;
    	while(node != null){
    		System.out.println(node.item);
    		node = node.next;
    	}
    }
    //倒序打印类
    public void reverseOrderPrint(){
    	Node<E> node = last;
    	while(node != null){
    		System.out.println(node.item);
    		node = node.prev;//找上一个
    	}
    }
	
	//节点类
    private static class Node<E> {
        E item;// 元素
        Node<E> next; //下一个节点地址
        Node<E> prev; // 上一个节点地址

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

测试类

public static void main(String[] args) {
		BidirectionalLinkedList<String> list = new BidirectionalLinkedList<>();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		list.add("ddd");
		list.add("eee");	
		
		list.positiveOrderPrint();
		
		System.out.println("-------------");
		list.reverseOrderPrint();
	}

测试结果

手写单双向链表_双向链表

手写单向链表

在双向链表的基础上就可以将单向链表写出来

单向链表类(SinglyLinkedList)

public class SinglyLinkedList<E> {
	
	//元素个数
    transient int size = 0;//0
   	//第一个节点
    transient Node<E> first;//null
    //最后一个节点
    transient Node<E> last;//null
    
    //添加类
    public void add(E e){
    	 //final Node<E> l = last;
         final Node<E> newNode = new Node<>(last, e, null);
         if (first == null)
             first = newNode;
         else
             last.next = newNode;
         last = newNode;
    }
    
    //正序打印类
    public void positiveOrderPrint(){
    	Node<E> node = first;
    	while(node != null){
    		System.out.println(node.item);
    		node = node.next;
    	}
    }
	
	//节点类
    private static class Node<E> {
        E item;// 元素
        Node<E> next; //下一个节点地址

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
        }
    }

测试类

public static void main(String[] args) {
		SinglyLinkedList<String> list = new SinglyLinkedList<>();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		list.add("ddd");
		list.add("eee");	
		
		list.positiveOrderPrint();

测试结果

手写单双向链表_双向链表_02


举报

相关推荐

0 条评论