简体   繁体   中英

addFirst() in java.util.LinkedList

This is for homework.

I am making a stack using a linked list. I have chosen to use the linked list from Java's java.util.LinkedList package. When I call the addFirst() method in my Main class, the program won't finish. It acts like an infinite loop, but as far as I know there are no loops involved. Here is the code:

package assignment3;

import java.util.LinkedList;

/**
 *
 * @author Eric
 */
public class LinkedListStack<T> {

    LinkedList linkedList = new LinkedList();


    public boolean isEmpty() {
     if (linkedList.isEmpty()) {
         return true;
     } else {
         return false;
     }
    }


    public int size() {
        int size = linkedList.size();

        System.out.println("The size of the stack is " + size);

        return size;
    }

// This is the problem method. 
    public void push(T element) {

        linkedList.addFirst(element);
    }


    public void pop() {
        while(!linkedList.isEmpty()){
            linkedList.removeFirst();
    }
    }


    public void peek() {
       while(!linkedList.isEmpty()){
            linkedList.peek();
        }

       System.out.println("The first element in the stack is " + linkedList.peek());
    }

}

This is the class Main that calls the push() method.

package assignment3;

/**
 *
 * @author Eric
 */
public class Main {
    public static void main(String args[]) {
        LinkedListStack linkedListStack = new LinkedListStack();

        linkedListStack.push(1); // This never finishes. 
        linkedListStack.peek();
        linkedListStack.size();
}

}

It's very hard to test LinkedListStack.java because I cannot push anything onto the stack. I have no idea what's wrong.

   while(!linkedList.isEmpty()){
        linkedList.peek();
    }

peek() will never change a linked list from nonempty to empty, since it doesn't change the list.

but as far as I know there are no loops involved

What do you think while is?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM