1、原地逆序
无头节点链表
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode * pre=nullptr;
ListNode * cur=pHead;
ListNode * next=nullptr;
//遍历所有节点,反转,依次,cur指向pre,做逆序
while(nullptr != cur){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
有头节点链表
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if((pHead == nullptr)||(pHead->next == nullptr)){
return nullptr;
}
ListNode * pre=nullptr;
ListNode * cur=nullptr;
ListNode * next=nullptr;
//从头节点之后的第一个节点开始遍历
cur = pHead->next;
next = cur->next;
//头节点之后的第一个节点指向null,做尾巴
cur->next = nullptr;
//头节点之后的第一个节点设置为pre
pre = cur;
//后移
cur = next;
//当前节点开始,反转,依次,cur指向pre,做逆序
while(cur->next != nullptr){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
//直到这时,cur走到原链表最后一个节点
//把原链表尾节点链到逆序好的链表的头部
cur->next = pre;
//把头节点接在最前面
pHead->next = cur;
return cur;
}
};
复杂度o(1),while循环
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 *firstNode = pHead;
//头节点传入
ListNode *newHead = recursiveReverse(firstNode);
return newHead;
}
ListNode* recursiveReverse(ListNode * node){
if(node->next == nullptr){
return node;
}else{
ListNode * newHead = recursiveReverse(node->next);
//找到尾节点之后一层一层回,node->next是尾节点,node为倒数第二个节点,node放到尾节点之后,最后是null,依次逆序
node->next->next = node;
node->next = nullptr;
return newHead;
}
}
};
复杂度o(n)
3、头插逆序
无头节点
/*
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 *curNode = pHead->next;
pHead->next = nullptr;
ListNode * next = nullptr;
while(curNode){
next = curNode->next;
curNode->next = pHead;
pHead = curNode;
curNode = next;
}
return pHead;
}
};
复杂度o(n)