堆栈C++链表实现方法(堆栈--数据结构)

堆栈C++链表实现方法(堆栈–链表)

需注意链表表头作为链表顶端

1.链表结构

typedef struct SNode *Stack;
struct SNode
{
    ElementType Data;
    struct SNode *Next;
};

2.堆栈初始化(生成空栈)

Stack CreateStack()
{
    Stack S;
    S=(Stack)malloc(sizeof(SNode));
    S->Next = NULL;
    return S;
}

3.判断堆栈S是否为空

int IsEmpty(Stack S)
{
    return(S->Next == NULL)
}

4.push操作

void Push(ELementType item, Stack S)
{
    struct Stack *TmpCell;
    TmpCell =(Stack)malloc(sizeof(SNode));
    TmpCell->Element=item;
    TmpCell->Next=S->Next;
    S->Next=TmpCell;
}

5.pop操作

ElementType Pop(Stack S)
{
   Stack *fistcell;
   if(isEmpty(S))
   {
       printf("堆栈空")return NULL;
   }
   else
   {
       firstcell = S->Next;
       S->Next = firstcell -> Next;
       TopELem = firstcell -> Element;
       free(firstcell);
       return TopElem;
   }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用链表实现堆栈C++代码: ```c++ #include <iostream> using namespace std; class Node { public: int data; Node* next; }; class Stack { private: Node* top; public: Stack() { top = nullptr; } void push(int val) { Node* newNode = new Node(); newNode->data = val; newNode->next = top; top = newNode; } bool isEmpty() { return top == nullptr; } int peek() { if (!isEmpty()) { return top->data; } else { cout << "Stack is empty!" << endl; return -1; } } void pop() { if (!isEmpty()) { Node* temp = top; top = top->next; delete temp; } else { cout << "Stack is empty!" << endl; } } }; int main() { Stack s; s.push(5); s.push(10); s.push(15); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; return 0; } ``` 在这个代码中,我们定义了两个类:`Node`和`Stack`。`Node`类表示堆栈中的一个节点,`Stack`类表示堆栈本身。在`Stack`类中,我们使用了链表实现堆栈。具体地,`top`指针指向堆栈的顶部。当我们向堆栈中添加一个元素时,我们创建一个新的节点,将其指向当前的`top`节点,然后将`top`指针指向新的节点。当我们从堆栈中删除一个元素时,我们删除顶部节点,并将`top`指针指向下一个节点。 在`main`函数中,我们创建了一个堆栈对象`s`,并向其中添加了三个元素。然后,我们使用`peek`函数查看堆栈的顶部元素,并使用`pop`函数删除堆栈的顶部元素。最后,我们使用`peek`函数再次查看堆栈的顶部元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值