面试题OJ:反转链表

反转链表是比较基础的问题,直接使用暴力法即可,这里采用了非递归和递归两个版本,大家在写代码时应该注意要在函数前面检查指针是否为NULL的问题,否则很容易会出现空指针的解引用问题:

这里直接给出代码,包含测试用例:

//面试题:反转链表

#include <iostream>
using namespace std;


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


class Solution 
{
public:
    //非递归
    static ListNode*  ReverseList(ListNode* pHead) 
    {
        if (pHead == NULL || pHead->next == NULL)
            return pHead;

        ListNode* pre = NULL;
        ListNode* next = NULL;

        while (pHead)
        {
            next = pHead->next;
            pHead->next = pre;
            pre = pHead;
            pHead = next;
        }
        return pre;
    }

    //递归版本
    static ListNode* ReverListR(ListNode* pHead)
    {
        if (pHead == NULL || pHead->next == NULL)
            return pHead;

        //找到链表中的最后一个不为NULL的节点
        ListNode* newHead = ReverListR(pHead->next);

        pHead->next->next = pHead;        //让当前节点的下一个节点的next指针指向当前节点
        pHead->next = NULL;               //让当前节点的next指针指向NULL

        return newHead;
    }

    static void PrintList(ListNode* pHead)
    {
        if (pHead == NULL)
            return;

        while (pHead)
        {
            cout << pHead->val << "->";
            pHead = pHead->next;
        }
        cout << "NULL"<<endl;
    }
};


void testNR()
{
    ListNode l1(1);
    ListNode l2(2);
    ListNode l3(3);
    ListNode l4(4);
    ListNode l5(5);
    ListNode l6(6);
    l1.next = &l2;
    l2.next = &l3;
    l3.next = &l4;
    l4.next = &l5;
    l5.next = &l6;
    Solution::PrintList(&l1);
    ListNode* newHead=Solution::ReverseList(&l1);
    Solution::PrintList(newHead);
}

void testR()
{
    ListNode l1(1);
    ListNode l2(2);
    ListNode l3(3);
    ListNode l4(4);
    ListNode l5(5);
    ListNode l6(6);
    l1.next = &l2;
    l2.next = &l3;
    l3.next = &l4;
    l4.next = &l5;
    l5.next = &l6;
    Solution::PrintList(&l1);
    ListNode* newHead = Solution::ReverListR(&l1);
    Solution::PrintList(newHead);
}

int main()
{
    //testNR();
    testR();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值