反转链表





#include "stdafx.h"
#include <string>
using namespace std;
#include <vector>
#include <stack>

typedef struct tag_listnode
{
    int data;
    struct  tag_listnode *next;

}listnode;

class Solution
{
public:

    listnode * reseveListnode(listnode *head)
    {
        listnode *node = head;
        listnode *next_node = head->next;

        while (node !=nullptr)
        {
            listnode *temp = next_node->next;  // 保存要断开的节点的下一个阶段,为了保持链表的遍历
            next_node->next = node;            // 翻转链表,将下个节点指向当前节
            //当前节点的头部为null、所以这里nextNode 变成 12-->null
            //同理下一次变成21->12->null
            node = next_node;                  // 更新当前节点变量
            next_node = temp;                  // 更新下个节点变量
        }
        head->next = NULL;                    // 将头部的next指向空,因为当前已经为最后的节点
        return node;
    }

};


int main()
{
    listnode head, node1, node2, node3, node4;
    node1.data = 11;  node1.next = &node2;
    node2.data = 22; node2.next = &node3;
    node3.data = 33; node3.next = &node4;
    node4.data = 44; node4.next = nullptr;
    head.next = &node1;
    Solution sou;
    listnode *result;
    result = sou.reseveListnode(&head);
    return 1;
}

posted on 2020-04-18 21:11  心中日月007  阅读(94)  评论(0编辑  收藏  举报