0

I am doing a stack using LinkedList and LinearNode Class in Java and I have a problem:

........

public BoundedStackADTLinkedImpl() {
        count = 0;
        top = null;
    }

public BoundedStackADTLinkedImpl(int stackCapacity) {
//I dont know how to do a builder using LinearNode with a initial Capacity  
}
    public BoundedStackADTLinkedImpl(int stackCapacity, T... initialContent) {
//Here I have the same problem.
    count = 0;
    top = new LinearNode<T>();
    for (T Vi : initialContent) {

        push(Vi);
    }

........

thanks!!!

4

2 回答 2

0

LinkedList添加项目时分配内存。初始容量没有意义。每个项目都有一个指向下一个项目的指针。

为什么不使用具有ensureCapacity()方法的Stack

在此处输入图像描述

于 2014-04-24T16:33:02.987 回答
0

你想要一个像这样的链接列表。请记住,您不能设置初始容量,因为容量取决于列表中元素的数量,您不会为它们预先创建空间。

public class LinkedList<T>
{
Node<T> topNode = null;

public LinkedList()
{
}

public LinkedList( Node<T>... nodes )
{
    for( Node<T> n : nodes )
    {
        push( n );
    }
}

public void push(Node<T> node)
{
    if ( topNode == null )
    {
        topNode = node;
        return;
    }

    Node<T> n = topNode;
    while( n.nextNode != null )
    {
        n = n.nextNode;
    }

    n.nextNode = node;
}

public Node<T> pop()
{
    if ( topNode != null )
    {
        Node<T> n = topNode;
        Node<T> p = n;
        while( n.nextNode != null )
        {
            n = n.nextNode;
            if ( n.nextNode != null )
            {
                p = n;
            }
        }

        p.nextNode = null;
        return n;
    }

    return null;
}
}

class Node <T>
{
Node<T> nextNode = null;
T value;

public Node( T val )
{
    value = val;
}
}
于 2014-04-24T16:40:56.033 回答