链表与下压堆栈 发表于 2024-08-06 阅读次数: Valine: 链表节点记录12345struct Node{ int item; Node *next;}; 构造链表为每个元素创造节点 123Node *first=new Node;Node *second=new Node;Node *third=new Node; 将每个结点的item域设为所需的值 123first->item="to";second->item="be";third->item="or" 设置next域来构造链表 12first->next=second;second->next=third; 下压堆栈(LIFO)在表头插入节点12345678void push(int item){ Node *newNode=new Node; newNode->item=item; newNode->next=first; first=newNode; N++;} 从表头删除节点1234567int pop(){ int item=first->item; first=first->next; N--; return item;} 遍历链表1234for(Node *x=first;x!=NULL;x=x->next){ //处理x->item} 完整实现123456789101112131415161718192021222324252627282930313233343536373839#include<bits/stdc++.h>using namespace std;int N;struct Node{ int item; Node *next;};Node *first = NULL;void push(int item){ Node *newNode=new Node; newNode->item=item; newNode->next=first; first=newNode; N++;}int pop(){ int item=first->item; first=first->next; N--; return item;}int main(){ push(1);push(3);push(2);push(4); for(Node *x=first;x!=NULL;x=x->next) { cout<<pop(); } return 0;}