Java的链表从数组插入问题

时间:2019-01-30 20:56:44

标签: java insert

我在Java中为作业分配创建了一个链表列表类,我的问题是,当我尝试使用from循环从另一个数组中插入数字时,它没有正确地将数字插入我的LinkedList类中。下面是链表类

class LinkedList
{
    //Class variables for the Linked List
    private static Node head;
    private static int numNodes; 
    public void addAtTail(int dat)
    {
        if (head == null)
        {
            head = new Node(dat);
            numNodes++;
        }
        else
        {
            Node temp = head;
            while(temp.next != null)
            {
                temp = temp.next;
            }

            temp.next = new Node(dat);
            numNodes++;
        }
    }
    public static int getSize()
    {
        return numNodes;
    }

    class Node
    {
        //Declare class variables
        private Node next;
        private int data;

        public Node(int dat)
        {
            data = dat;
        }

        public Object getData()
        {
            return data;
        }
    }

    public static void printList()
    {
        Node temp = head;
        while(temp != null)
        {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }


        System.out.println();
     }



    public static void main(String [] args)
    {
        int[] g = {4, 2, 3, 1, 5};
        LinkedList L = new LinkedList();

        for(int u = 0; u < g.length; u++)
            {
                L.addAtTail(g[u]);
            }


        L.printList();
    }
}

代码将其打印出来 4 2 3 1 5 5 3 2 1 4 2 5 1 4 3 5 2 4 3 1 4 1 2 3 5 4 2 3 1 5

何时只打印4 2 3 1 5

0 个答案:

没有答案