Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

java - How to write this function?

Write a method/function, called queues2stack, in pseudocode (or Java without using specialised libraries) that receives two queues and creates a single stack that contains all the information from each of the queues. Each of the two input queues contains a set of integers and is ordered by having the integers in decreasing order (highest at the front of the queue, lowest at the end). Your algorithm should always add the highest valued entries. The resulting stack will have the same number of entries as the sum of the number of entries in the two queues.

What I've written:

void queues2stack {
  while (!q1.empty & q2.empty) {    
    if (q1.pop () > q2.pop()) 
      s.push(q1.pop)
    else 
      s.push(q2.pop)
  }
    
  while (!q1.empty()) {
    s.push(q1.pop)
  }
  
  while !q2.empty() {
    s.push(q2.pop)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use peek() to check the values without removing them.

void queues2stack {
  while (!q1.empty & q2.empty) {    
    if (q1.peek() > q2.peek()) 
      s.push(q1.pop())
    else 
      s.push(q2.pop())
  }
    
  while (!q1.empty()) {
    s.push(q1.pop)
  }
  
  while !q2.empty() {
    s.push(q2.pop)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...