题目描述
输入一个链表,反转链表后,输出新链表的表头。
题目分析:对于链表问题,一定要注意是否带有头结点,因为有无头结点在编程时存在一些细节需要注意。对于链表的反转有两种办法:
1、头插法:将结点逐个从链表中摘下,并将该节点插入头结点之后。
2、原地反转:如果访问结点不为空,记下当前结点(记录结点),访问结点后移,记录结点指向头结点,头结点指向记录结点。
具体代码:
不带头结点原地反转
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {//不带头结点原地反转
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == nullptr)
return nullptr;
ListNode* pNode = pHead;
ListNode* Head = nullptr;
while(pNode != nullptr) {
ListNode* cur = pNode;
pNode = pNode->next;
cur->next = Head;
Head = cur;
}
return Head;
}
};
带头结点原地反转
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {//带头结点原地反转
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == nullptr)
return nullptr;
ListNode* pNode = pHead->next;
pHead->next = nullptr;
ListNode* Head = pHead;
while(pNode != nullptr) {
ListNode* cur = pNode;
pNode = pNode->next;
cur->next = Head->next;
Head->next = cur;
}
return Head;
}
};
带头结点头插法
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {//带头结点头插法
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == nullptr)
return nullptr;
ListNode* pNode = pHead->next,*qNode;
pHead->next = nullptr;
while(pNode != nullptr)
{
qNode = pNode->next;
pNode->next = pHead->next;
pHead->next = pNode;
pNode = qNode;
}
return pHead;
}
};