美文网首页
链表翻转

链表翻转

作者: SeatonLv | 来源:发表于2022-06-29 19:09 被阅读0次

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

    20200926222143340.gif
    #include <iostream>
    #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:"<<head->valueT<<endl;
            head = head->next;
        }
    
        cout<<"after reverse:-------------------------------"<<endl;
    
        LinkNode*  reverseNode = Reverse(node);
    
        while (reverseNode!= nullptr)
        {
            cout<<"value:"<<reverseNode->valueT<<endl;
            reverseNode = reverseNode->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

    相关文章

      网友评论

          本文标题:链表翻转

          本文链接:https://www.haomeiwen.com/subject/vjkxbrtx.html