zoukankan      html  css  js  c++  java
  • 初级算法

    顾名思义, 就是将链表的所有结点反转。

    解释见:【剑指offer】反转链表,C++实现(链表)

    代码:

    #include <iostream>
    
    struct NodeList {
        int data;
        struct NodeList* next;
        NodeList() :data(0), next(NULL) {}
        NodeList(int data) :data(data), next(NULL) {}
        NodeList(int data,NodeList *next) :data(data), next(next) {}
    };
    
    class Solution {
    public:
        void add(NodeList* head, int dat) {
            NodeList* newnode = new NodeList();
            newnode->data = dat;
            newnode->next = NULL;
    
            NodeList* node = head;
            while (node->next != NULL)
            {
                node = node->next;
            }
    
            node->next = newnode;
        }
        NodeList *reverse(NodeList* head)
        {
            NodeList* node = head;
            NodeList* temp = NULL;
            NodeList* reverhead = NULL;
            NodeList* pnext = NULL;
    
            while (node != NULL)
            {
                pnext = node->next;
                if (pnext == NULL)
                {
                    reverhead = node;
                }
    
                node->next = temp;
                temp = node;
                node = pnext;
            }
    
            return reverhead;
        }
    
    
    
        void print(NodeList* head)
        {
            NodeList* node = head;
            while (node!= NULL)
            {
                std::cout << node->data << " ";
                node = node->next;
            }
            std::cout << std::endl;
        }
    };
    
    
    int main() 
    {
        Solution s;
        NodeList* node = new NodeList(1,NULL);
        for (int i = 2; i < 11; i++)
        {
            s.add(node, i);
        }
        s.print(node);
    
        NodeList *revernode = s.reverse(node);
        s.print(revernode);
        return 0;
    }

    打印:

    1 2 3 4 5 6 7 8 9 10
    10 9 8 7 6 5 4 3 2 1
  • 相关阅读:
    输出流对象
    1.2最简单的c++程序
    c++的初步认识
    理想程序员
    从字符数组中删除字符
    打印杨辉三角
    旋转数组
    找出1000以内的所有完数
    计算兔子的总数
    101-200有多少个素数?
  • 原文地址:https://www.cnblogs.com/strive-sun/p/14439915.html
Copyright © 2011-2022 走看看