链表翻转

顾名思义:链表反转
eg:4--->3---->2--->1转为1-->2--->3---->4
实现原理如下 就是把当前节点的next 往前赋值,然后更新cur 和pre 直到 cur==null

20200926222143340.gif
#include 
#include "LinkNode.h"
using namespace  std;


LinkNode* Reverse(LinkNode* head)
{
    LinkNode* pre = nullptr;
    LinkNode* cur = head;
    while (cur)
    {
        LinkNode* tem = cur->next;
        cur->next = pre;

        pre = cur;
        cur = tem;
    }

    return  pre;
}

int main() {
    std::cout << "Hello, World!" << std::endl;


    LinkNode *node3 = new LinkNode();
    node3->valueT = 3;
    node3->next = nullptr;

    LinkNode *node2 = new LinkNode();
    node2->valueT = 2;

    LinkNode *node1 = new LinkNode();
    node1->valueT = 1;

    LinkNode *node = new LinkNode();
    node->valueT = 0;

    node->next = node1;
    node1->next = node2;
    node2->next = node3;

    LinkNode* head = node;

    while (head!= nullptr)
    {
        cout<<"value:"<valueT<next;
    }

    cout<<"after reverse:-------------------------------"<valueT<next;
    }


    return 0;
}

数据结构类

#ifndef LINKNODE_H
#define LINKNODE_H


class LinkNode {
public:
    int valueT;
    LinkNode* next;


public:
    LinkNode();
    ~LinkNode();
};


#endif //CLIONTEST_LINKNODE_H

------------------------------------------------------------------------------------------------------------------------

//
// Created by Administrator on 2022/6/29.
//

#include "LinkNode.h"

LinkNode::LinkNode() {


}
LinkNode::~LinkNode() {


}

打印结果


image.png

你可能感兴趣的:(链表翻转)