您的位置:首页 > 职场人生

面试题OJ:反转链表

2017-01-23 13:16 176 查看
反转链表是比较基础的问题,直接使用暴力法即可,这里采用了非递归和递归两个版本,大家在写代码时应该注意要在函数前面检查指针是否为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反转链表 链表