Use the Linked List to write out the functions of the stack's Delete (Pop) for its class

使用 Linked List 為 Stack 的類別寫出其 Delete(Pop)的函式(Functions)

 已知使用 Linked List 為 Stack 的類別(Class)宣告如下,請寫出其 Delete(Pop)的函式(Functions)。(10 分)

s

x wt

v y

z

u

1

1

1

1

1

1

110

10

10

10

10

10

template <class T>

class Node {

friend LinkedStack<T>;

private :

T data;

Node<T> *link;

};

template <class T>

class LinkedStack {

public :

LinkedStack() {top = 0;}

~LinkedStack();

bool IsEmpty() const {return top == 0;}

bool IsFull() const ;

T Top() const ;

LinkedStack<T>& Add(const T& x);

LinkedStack<T>& Delete(T& x);

private :

Node<T> *top; // pointer to top node

};

以下是使用 Linked List 实现的 Stack 类的 Delete(Pop)函数的示例代码:


```cpp

template <class T>

LinkedStack<T>& LinkedStack<T>::Delete(T& x) {

    if (IsEmpty()) {

        cout << "Stack is empty. Cannot pop." << endl;

        return *this;

    }

    

    Node<T> *temp = top; // Store the current top node

    x = top->data; // Get the data to be deleted

    

    top = top->link; // Move the top pointer to the next node

    delete temp; // Delete the old top node

    

    return *this;

}

```


这个函数会检查栈是否为空,如果为空,则无法执行弹出操作。否则,它会将栈顶的节点弹出,并返回其值。


Comments

Popular posts from this blog

How to write data into a excel file using vbscript

Format date as yyyy-mm-dd using vbscript