# 使用（键，值）实现栈

go评论62阅读模式

Implementing Stack With (Key,Value)

# 问题

I am wondering if I can implement a stack with (Key, Value) like below:

``````public static void main(String[] args) {
PriorityQueueStack<Integer, V> s = new PriorityQueueStack<>();
s.push(1, 'A');
s.push(2, 'B');
s.push(3, 'C');
s.push(4, 'D');
}
``````

My class implementation is like below:

``````public class PriorityQueueStack<E> extends SortedPriorityQueue<Integer, E> implements
PriorityQueue<Integer, E>{
``````

Is there a way to implement it with (Key, Value) as I have searched I couldn't find any resource of such an implementation.

The output should be like this:

``````(1,'A'), (2,'B'), ..... and so on
``````

I am wondering if I can implement a stack with (Key, Value) like below:

``````    public static void main(String[] args) {
PriorityQueueStack&lt;Integer,V&gt; s = new PriorityQueueStack&lt;&gt;();
s.push(1,&#39;A&#39;);
s.push(2,&#39;B&#39;);
s.push(3,&#39;C&#39;);
s.push(4,&#39;D&#39;);
``````

My class implementation is like below:

``````  public class PriorityQueueStack&lt;E&gt; extends SortedPriorityQueue&lt;Integer, E&gt; implements
PriorityQueue&lt;Integer, E&gt;{
``````

Is there a way to implement it with (Key, Value) as I have searched I couldn't find any resource of such an implementation.

The output should be like this:

`````` (1,&#39;A&#39;),(2,&#39;B&#39;)..... and so on
``````

# 答案1

It could be done by creating a separate class for key-value pair and adding an object of that class in the Stack.

``````创建一个**用于键值对的独立类**，然后**将该类的对象添加到堆栈中**。
``````
``````class Pair{

int key;
char value;

public Pair(int key,char value){
this.key = key;
this.value = value;
}

}

public class Main {
public static void main(String[] args) {
Stack<Pair> stack = new Stack<>();
stack.push(new Pair(1,'A'));
stack.push(new Pair(2,'B'));
stack.push(new Pair(3,'C'));
stack.push(new Pair(4,'D'));
// Pair p = stack.pop();
// System.out.println(p.key+" "+p.value);
}
}
``````

It could be done by creating a separate class for key-value pair and adding an object of that class in the Stack.

``````class Pair{

int key;
char value;

public Pair(int key,char value){
this.key = key;
this.value = value;
}

}

public class Main {
public static void main(String[] args) {
Stack&lt;Pair&gt; stack = new Stack&lt;&gt;();
stack.push(new Pair(1,&#39;A&#39;));
stack.push(new Pair(2,&#39;B&#39;));
stack.push(new Pair(3,&#39;C&#39;));
stack.push(new Pair(4,&#39;D&#39;));
// Pair p = stack.pop();
// System.out.println(p.key+&quot; &quot;+p.value);
}
}
``````

• 本文由 发表于 2020年8月2日 22:11:37
• 转载请务必保留本文链接：https://go.coder-hub.com/63216981.html
• algorithm
• class
• data-structures
• java
• oop

go 33

go 34

go 32

go 29