zoukankan      html  css  js  c++  java
  • 逆转单链表

    问题

    思路

    cur = pre->next;
    post = cur=>next;
    cur->next = pre;
    cur = post;

    代码 

    ListNode* reverseList(ListNode *root)
    {
        if (root == NULL)
            return root;
        ListNode *cur = root;
        ListNode *pre = NULL;
        ListNode *post = NULL;
        ListNode *revRoot = NULL;
        while (cur != NULL)
        {
            post = cur->next;
            if (post == NULL)
                revRoot = cur;
            cur->next = pre;
            pre = cur;
            cur = post;
        }
        return revRoot;
    }

    完整执行

    #include <iostream>
    using namespace std;
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int v) : val(v), next(NULL) {}
    };
    
    ListNode* createList()
    {
        ListNode *root = new ListNode(0);
        ListNode *p1 = new ListNode(1);
        ListNode *p2 = new ListNode(2);
        ListNode *p3 = new ListNode(3);
        root->next = p1;
        p1->next = p2;
        p2->next = p3;
        return root;
    }
    
    ListNode* reverseList(ListNode *root)
    {
        if (root == NULL)
            return root;
        ListNode *cur = root;
        ListNode *pre = NULL;
        ListNode *post = NULL;
        ListNode *revRoot = NULL;
        while (cur != NULL)
        {
            post = cur->next;
            if (post == NULL)
                revRoot = cur;
            cur->next = pre;
            pre = cur;
            cur = post;
        }
        return revRoot;
    }
    
    void deleteList(ListNode *root)
    {
        ListNode *p = root;
        while(root != NULL)
        {
            p = root->next;
            delete(root);
            root = p;
        }
    }
    
    void tranverse(ListNode* root)
    {
        while(root != NULL)
        {
            cout << root->val << " ";
            root = root->next;
        }
        cout << endl;
    }
    
    int main()
    {
    
        ListNode *root = createList();
    
        tranverse(root);
        root = reverseList(root);
        tranverse(root);
         
        deleteList(root);
    }
    View Code

    结果

    0 1 2 3 
    3 2 1 0
  • 相关阅读:
    使用header发送状态代码
    apache rewrite模块基础知识
    Deprecated: Function set_magic_quotes_runtime() is deprecated
    Xmind3.3强烈推荐
    windows 下安装svn服务
    Zend Studio 8
    mysql触发器
    程序员每天该做的事(转载)
    你真的了解.NET中的String吗?
    VS2005中Build顺序的设定
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3524888.html
Copyright © 2011-2022 走看看