逆置单链表

逆置单链表

问题描述:实现算法,将一个单链表逆置。(将一个单链表中的所有节点按照逆序存放)

分析:将一个单链表逆置其实就是用头插法建立单链表。定义一个空链表,分别将元单链表中的第一个节点、第二个节点一直到第n个节点插入新单链表的头部,即插入的节点成为新单链表的第一个节点。

// 假设链表节点的数据域包含学号、姓名、地址
#include <iostream>
#include <string>

using namespace std;

struct node
{
    int no;
    string name;
    string addr;
    node* next;
};

node* createList();
node* reverseList(node*);
void dispList(node*);

int main()
{
    node *head{createList()};

    dispList(head);
    head = reverseList(head);
    dispList(head);

    return 0;
}

node* createList()
{
    node *head{nullptr}, *pre, *cur;    // head表示表头,pre表示当前插入新节点前的最后一个节点
    int n;
    cout << "请输入节点个数" << endl;
    cin >> n;
    for (int i{}; i < n; i++) {
        cur = new node;
        cur->next = nullptr;
        if (!head) {    // 若head为NULL
            head = cur; // 则将第一个节点指针赋给head
        } else {
            pre->next = cur;    // 否则,将新节点连接入链表内(插入至链表尾部)
        }
        cin >> cur->no >> cur->name >> cur->addr;
        pre = cur;
    }
    return head;    // 返回头指针
}

node* reverseList(node* h)
{
    node* hh{new node};
    hh->next = nullptr;
    for (node *p{h}, *pre; p; ) {   // p指向原单链表的第一个节点
        pre = p;    // pre指向待插入的节点
        p = p->next;    // p指向当前的下一个节点
        pre->next = hh->next;   // 将hh->next赋给pre->next, 将pre连接至逆置后单链表的原节点
        hh->next = pre; // 将pre插入逆置后的单链表
    }
    return hh->next;    // 返回逆置后单链表的头指针
}

void dispList(node* h)
{
    cout << "学号\t" << "姓名\t" << "地址" << endl;
    for (node* p{h}; p; p = p->next) {
        cout << p->no << "\t" << p->name << "\t" << p->addr << "\t" << endl;
    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值