java stack 实现_Swift Stack实现

java stack 实现

In this tutorial, we’ll be discussing and implementing the Data Structure: Stacks, using Swift. We’ll see how Swift Generics make it easy to create Generic Stacks.

在本教程中,我们将使用Swift讨论和实现数据结构:堆栈。 我们将看到Swift泛型如何使创建泛型堆栈变得容易。

迅捷堆叠 (Swift Stack)

Stacks are a data structure that is used to hold the data in a particular order.

堆栈是一种数据结构,用于按特定顺序保存数据。

Let’s see how they are ordered:

让我们看看它们的顺序:

The order is like a pile of books. You can keep inserting a new book in the collection at the top.
You can only remove or view the topmost book. That means to remove the bottom-most book, you’ll have to remove all the books above.

订单就像一堆书。 您可以继续在顶部的收藏夹中插入一本新书。
您只能删除或查看最顶层的书。 这意味着要删除最底层的书,您必须删除上面的所有书。

This order is known as Last in First Out(LIFO).

此顺序称为后进先出 (LIFO)。

Following diagram showcases an example:

下图展示了一个示例:

  • Push is used to insert an element to a stack.

    推入用于将元素插入堆栈。
  • Pop is used to remove the topmost element.

    Pop用于删除最上面的元素。
  • Peek is used to view the topmost element.

    Peek用于查看最上方的元素。

By default, if the Stack is empty, it returns a nil.

默认情况下,如果堆栈为空,则返回nil。

We can create Stacks using Arrays, LinkedList etc. We’ll use Arrays for this tutorial.
我们可以使用数组,LinkedList等创建堆栈。在本教程中,我们将使用数组。

堆栈的重要用例 (Important Use case for Stacks)

In a music playlist application, where songs are queued and set on shuffle, often you realize that going back and forth changes the next song to a new random song.

在音乐播放列表应用程序中,歌曲在队列中排队并随机播放,您常常会意识到,来回移动会将下一首歌曲更改为新的随机歌曲。

This happens through Stacks. The latest song is added on top of a stack. If you don’t like that song, you can always press back (pop) and forward(push) to insert a new random song in the queue.

这是通过堆栈发生的。 最新的歌曲被添加到堆栈的顶部。 如果您不喜欢那首歌,可以随时按向后(pop)和前进(push)在队列中插入新的随机歌曲。

Let’s launch the XCode playground and implement Swift Stacks.

让我们启动XCode操场并实现Swift Stacks。

创建堆栈 (Create a Stack)

We can create a Stack in Swift in the following way:

我们可以通过以下方式在Swift中创建一个Stack:

struct Stack {
  private var myArray: [String] = []
}

We’ve defined a structure Stack that would contain Array of Strings.

我们定义了一个结构Stack,其中包含字符串数组。

Let’s define the functions push, pop and peek in the Swift Structure.

让我们定义Swift结构中的push,pop和peek功能。

Push

mutating func push(_ element: String) {
        myArray.append(element)
    }

This push function appends the new element to the LAST of the array.

此push函数将新元素附加到数组的LAST。

Pop

流行音乐

mutating func pop() -> String? {
  return myArray.popLast()
}

This pop function removes the LAST element using the popLast() function available with Swift Arrays.
We’ve used an Optional return type String since it can return a nil.

此pop函数使用Swift数组可用的popLast()函数删除LAST元素。
我们使用了可选的返回类型String,因为它可以返回nil。

Peek

窥视

func peek() -> String {
        guard let topElement = myArray.last else { print("This stack is empty.") }
        return topElement
    }

If you want to show a custom error message, instead of using Optionals, use the guard let statement of Swift.

如果要显示自定义错误消息,请使用Swift的guard let语句,而不是使用Optionals。

This is how our final structure looks in the XCode Playground.

这就是我们最终结构在XCode Playground中的外观。

struct Stack {
    private var myArray: [String] = []
    
    mutating func push(_ element: String) {
        myArray.append(element)
    }
    
    mutating func pop() -> String? {
        return myArray.popLast()
    }
    
    func peek() -> String {
        guard let topElement = myArray.last else {return "This stack is empty."}
        return topElement
    }
}

var stack = Stack()
stack.peek()
stack.push("Swift Arrays")
stack.push("Swift LinkedList")
stack.push("Swift Stack")
print(stack)
stack.peek()
stack.pop()
stack.pop()
stack.pop()
stack.peek()
stack.pop()

print stack prints the array

打印堆栈打印数组

The result of the above Stack operations is:

swift stack string array operations output

上述堆栈操作的结果是:

The above Stack can only hold Strings. Besides, it doesn’t print the stack contents beautifully.

上面的堆栈只能容纳字符串。 此外,它不能很好地打印堆栈内容。

For that, we can use the CustomStringConvertible protocol as an Extension on our Structure.

为此,我们可以使用CustomStringConvertible协议作为结构的扩展。

Let’s create an extension for the Stack structure below:

让我们为下面的Stack结构创建一个扩展:

extension Stack: CustomStringConvertible {
    var description: String {
        let header = "****Swift Stack Begin****\n"
        let bottomDivider = "\n****Swift Stack End*****\n"
        
        let elements = myArray.joined(separator: "\n")
        
        return header + elements + bottomDivider
    }
}

Following is the output from stack.description

以下是stack.description的输出

It’s printing the stack in the order in which it was pushed. We need to reverse it using the reversed() method:

它按推入的顺序打印堆栈。 我们需要使用reversed()方法将其反转:

let elements = myArray.reversed().joined(separator: "\n")

The correct stack order is now:

swift stack custom string convertible correct

现在正确的堆叠顺序为:

快速通用堆栈 (Swift Generic Stacks)

Let’s make the above Swift stack generic.

让我们使上述Swift堆栈通用。

You just need to update your Stack definition with a generic parameter in brackets!

您只需要使用方括号中的通用参数更新堆栈定义!

struct Stack<T> {
    private var myArray: [T] = []
    
    mutating func push(_ element: T) {
        myArray.append(element)
    }
    
    mutating func pop() -> T? {
        return myArray.popLast()
    }
    
    func peek() -> T? {
        return myArray.last
    }
}

Note: In the CustomStringConvertible protocol, we were joining the elements using joined.
This won’t work for non-string elements. So we need to first map the element to a string using the map operator and then join.

注:在CustomStringConvertible协议,我们加入的元素使用joined
这不适用于非字符串元素。 因此,我们需要先使用map运算符将元素映射到字符串,然后再进行连接。

let elements = myArray.reversed().map{ "\($0)" }.joined(separator: "\n")

$0 refers to the current element that’s being mapped.

$ 0表示正在映射的当前元素。

We’ve used a Stack of type Any. You can pass anything in place.

我们使用了Any类型的Stack。 您可以通过任何地方。

This brings an end to this tutorial on Swift Stack implementation.

这样就结束了有关Swift Stack实现的本教程。

翻译自: https://www.journaldev.com/21287/swift-stack-implementation

java stack 实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值