码迷,mamicode.com
首页 > 其他好文 > 详细

递归、非递归 反转单链表

时间:2014-09-12 23:21:44      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   art   div   

定义链表结构

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int v) : val(v), next(NULL) {}
};

非递归反转单链表

ListNode* reverse(ListNode *root)
{
    if (root == NULL || root->next == NULL)
        return root;
    ListNode *cur = root->next;
    root->next = NULL;
    while (cur != NULL)
    {
        ListNode *tmp = cur->next;
        cur->next = root;
        root = cur;
        cur = tmp;
    }
    return root;
}

递归反转单链表

void reverseRec(ListNode *root, ListNode *&head)
{
    if (root == NULL)
        return;
    if (root->next == NULL)
    {
        head = root;
        return;
    }
    reverseRec(root->next, head);
    root->next->next = root;
    root->next = NULL;
}

测试

bubuko.com,布布扣
#include <iostream>
using namespace std;
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int v) : val(v), next(NULL) {}
};
ListNode* createList(ListNode *root)
{
    if (root == NULL)
    {
        ListNode *root = new ListNode(0);
        ListNode *p1 = new ListNode(1);
        ListNode *p2 = new ListNode(2);
        root->next = p1;
        p1->next = p2;
        return root;
    }
}
void tranverse(ListNode *root)
{
    while (root != NULL)
    {
        cout << root->val << " ";
        root = root->next;
    }
    cout << endl;
}
void deleteList(ListNode *root)
{
    while (root != NULL)
    {
        delete root;
        root = NULL;
    }
}
ListNode* reverse(ListNode *root)
{
    if (root == NULL || root->next == NULL)
        return root;
    ListNode *cur = root->next;
    root->next = NULL;
    while (cur != NULL)
    {
        ListNode *tmp = cur->next;
        cur->next = root;
        root = cur;
        cur = tmp;
    }
    return root;
}
void reverseRec(ListNode *root, ListNode *&head)
{
    if (root == NULL)
        return;
    if (root->next == NULL)
    {
        head = root;
        return;
    }
    reverseRec(root->next, head);
    root->next->next = root;
    root->next = NULL;
}
    
int main()
{
    ListNode *root = createList(root);
    //ListNode *root = NULL; 
    tranverse(root);
    root = reverse(root);
    tranverse(root);

    ListNode *head = NULL;
    reverseRec(root, head);
    tranverse(head);
    
    deleteList(head);
}
View Code

 

递归、非递归 反转单链表

标签:style   blog   http   color   io   os   ar   art   div   

原文地址:http://www.cnblogs.com/kaituorensheng/p/3955101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!