zoukankan      html  css  js  c++  java
  • golang 栈操作

    Monk's Love for Food
     

    Our monk loves food. Hence,he took up position of a manager at Sagar,a restaurant that serves people with delicious food packages. It is a very famous place and people are always queuing up to have one of those packages. Each package has a cost associated with it. The packages are kept as a pile. The job of a manager is very difficult. He needs to handle two types of queries:

    1) Customer Query:
    When a customer demands a package, the food package on the top of the pile is given and the customer is charged according to the cost of the package. This reduces the height of the pile by 1. 
    In case the pile is empty, the customer goes away empty-handed.

    2) Chef Query:
    The chef prepares a food package and adds it on top of the pile. And reports the cost of the package to the Manager.
    Help him manage the process.

    Input:
    First line contains an integer Q, the number of queries. Q lines follow.
    A Type-1 ( Customer) Query, is indicated by a single integer 1 in the line.
    A Type-2 ( Chef) Query, is indicated by two space separated integers 2 and C (cost of the package prepared) .

    Output:
    For each Type-1 Query, output the price that customer has to pay i.e. cost of the package given to the customer in a new line. If the pile is empty, print "No Food" (without the quotes).

    Constraints:
    1 ≤ Q ≤ 105
    1 ≤ C ≤ 107

    用到了slice的两个基本方法  stack = stack[0:stackLength-1] 就是将最后的一个元素删除,slice中下标用的其实是相当[0,stackLength-1} 就是从前标开始,包括前标到后标,但是不包括后标,下来就是往slice中添加元素。

    package main
    
    import "fmt"
    
    
    var stack []int
    
    func main() {
    	var inputCount int
    	fmt.Scanln(&inputCount)
    	
    	stack = make([]int,0,0)
    	
    	var flag,value int
    	var stackLength int
    	for i:=0;i<inputCount;i++{
    	    fmt.Scanln(&flag,&value)
    	    stackLength = len(stack)
    	    if(flag ==1){
    	        if(stackLength == 0){
    	            fmt.Println("No Food")
    	        }else{
    	           fmt.Println(stack[stackLength-1])
    	           stack = stack[0:stackLength-1]
    	        }
    	    }else{
    	       stack = append(stack,value) 
    	    }
    	}
    }
    

      

     
  • 相关阅读:
    java设计模式——多例模式
    Java多例模式
    设计模式(四)——多例模式
    IoC是一个很大的概念,可以用不同的方式实现。
    现有的框架实际上使用以下三种基本技术的框架执行服务和部件间的绑定:
    IOC关注服务(或应用程序部件)是如何定义的以及他们应该如何定位他们依赖的其它服务
    IoC最大的好处是什么?
    Java – Top 5 Exception Handling Coding Practices to Avoid
    @Spring MVC请求处理流程
    Spring Bean的生命周期(非常详细)
  • 原文地址:https://www.cnblogs.com/jfliuyun/p/6848348.html
Copyright © 2011-2022 走看看