借助栈逆置单链表

编写算法Reverse(LinkList &L),要求借助于栈将一个带头结点的单链表L逆置。其中栈的初始化操作、入栈操作和出栈操作算法名分别为InitStack(&S)、Push(&S,e)、Pop(&S,&e)。
注意:new你也可以用malloc delete就换成free

cpp 复制代码
typedef int ElemType;
typedef  struct  SNODE

{
    ElemType  data;

    struct  SNODE* next;

}SNODE, * LinkStack;

void InitStack(LinkStack& l)
{
    l = new SNODE;
    l->next = nullptr;
}
void push(LinkStack& l, ElemType x)
{
    LinkStack p = new SNODE;
    p->data = x;
    p->next = l->next;
    l->next = p;
}
void pop(LinkStack& l,ElemType& e)
{
    if (!l->next) return;
    
   
    LinkStack p = l->next; e = p->data;
    LinkStack q = p->next;
     l->next=q;
    delete p;
}
int empty(LinkStack& l)
{
    if (l->next == nullptr)  return 1;
    else return 0;
}

typedef struct  s {

    ElemType      data;      // 数据域

    struct s* next;   // 指针域

} LNode, * LinkList;


void Reverse(LinkList& l)
{
    LinkList p = l->next;
    LinkList r = l;
    LinkStack s;
    int e;
    InitStack(s);
    while (p)
    {
        push(s, p->data);
        p = p->next;
    }
    while (!empty(s))
    {
       pop(s, e);
       LinkList q = new LNode;
       q->data = e;
       q->next = nullptr;
       r->next = q;
       r = q;
    }

}
相关推荐
散11231 分钟前
01数据结构-B树练习及B+树特点
数据结构·b树
书院门前细致的苹果1 小时前
MySQL 中的 B+树和 B树的区别详解
数据结构·数据库·mysql
半桔2 小时前
【STL源码剖析】二叉世界的平衡:从BST 到 AVL-tree 和 RB-tree 的插入逻辑
java·数据结构·c++·算法·set·map
塔中妖3 小时前
【华为OD】分割数组的最大差值
数据结构·算法·华为od
凯子坚持 c3 小时前
Redis 核心数据结构:String 类型深度解析与 C++ 实战
数据结构·c++·redis
songx_994 小时前
leetcode29( 有效的括号)
java·数据结构·算法·leetcode
爱编程的化学家10 小时前
代码随想录算法训练营第六天 - 哈希表2 || 454.四数相加II / 383.赎金信 / 15.三数之和 / 18.四数之和
数据结构·c++·算法·leetcode·双指针·哈希
papership15 小时前
【入门级-算法-6、排序算法: 插入排序】
数据结构·算法·排序算法
得意霄尽欢15 小时前
Redis之底层数据结构
数据结构·数据库·redis
I'm a winner16 小时前
第五章:Python 数据结构:列表、元组与字典(二)
数据结构·python