生成随机数链表反转

涉及知识点:①生成随机数   ②将普通数组转化为链表  ③链表反转

#include<iostream>
#include<cstdlib>

using namespace std;

typedef struct node//声明结构体
{
    int data;
    node* next;
};


struct node* reverse(struct node* head)//链表逆序函数
{
    if (head->next == NULL || head->next->next == NULL)
    {
        return head;   //链表为空或只有一个元素则直接返回
    }

    node* t = NULL;
    node* p = head->next;
    node* q = head->next->next;
    while (q != NULL)
    {
        t = q->next;
        q->next = p;
        p = q;
        q = t;
    }

//此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素
    head->next->next = NULL;  //设置链表尾
    head->next = p;           //调整链表头
    return head;

}

int main() {
    cout << "原始链表:" << endl;
    int x[10];
    //生成随机数组并存入链表之中
    srand(time(0));
    for (int i = 0; i < 10; i++) {
        x[i] = rand() % (100) + 1;//初始化随机数组
    }
    //用头插法将数组插入链表中
int k = 0; struct node* head = NULL, * p;
    for (k = 0; k < 10; k++) {
        p = (struct node*)malloc(sizeof(struct node));
        p->data = x[k];
        p->next = head;
        head = p;
    }
    //输出原始链表
    p = head;
    cout << "head" << head->data << '\n';
    while (p != NULL) {
        cout << p->data << '\t';
        p = p->next;
    }

    cout << "\n倒序后的链表" << endl;
    reverse(head);
    cout << "head" << head->data << '\n';//这个head是没有变得。。。
    struct node* y = head->next;
    int t = head->data;
    while (y != NULL) {
        cout << y->data << '\t';
        y = y->next;
    }
    cout << t << endl;

}

这个反转函数直接参照的:

C++ ——实现链表反转逆序_bingocoder的博客-CSDN博客_c++链表反转

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值