Java实现链表结构的头插法与尾插法

package data_structure;

import java.util.Scanner;

public class List<Item> {

    @SuppressWarnings("hiding")
    public class Node<Item> {
        Item content;
        Node<Item> next;

        public Node(Item content, Node<Item> next) {
            this.content = content;
            this.next = next;
        }
    }

    Node<Item> head;
    Node<Item> tail;
    int length;

    public List() {
        this.head = null;
        this.tail = null;
        this.length=0;
    }

    public void headinsert(Item content) {
        this.head = new Node<Item>(content, this.head);
        if (this.tail== null) {
            this.tail = this.head;
        }
        length++;
    }

    public void tailinsert(Item content) {
        if(this.tail==null){
        this.tail = new Node<Item>(content, null);
        this.head = this.tail;
        }else{
            this.tail.next=new Node<Item>(content,null);
            this.tail = this.tail.next;
        }
        this.length++;
    }

    public void show() {
        while (this.head!=null) {
            System.out.println(this.head.content);
            this.head=this.head.next;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> first = new List<Integer>();
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        while (number != -1) {
            if (number % 2 == 0) {
                first.headinsert(number);
            } else {
                first.tailinsert(number);
            }
            number = input.nextInt();
        }
        input.close();
        first.show();

    }

}

猜你喜欢

转载自blog.csdn.net/zhangxiaojiakele/article/details/70196812