先给出链表节点定义吧
#include <utility>
#include <cstdint>
typedef struct Node{
struct Node * __Next__ { nullptr };
uint32_t __Value__ {};
} Node;
总的来说,一般遇到的链表反转就两种情况:部分反转和整个反转
先来看整个反转:
比如: * &head -> 1→2→3→∅,改成 ∅←1←2←3 <- * &head
思路是让下一个节点指向当前节点
有迭代法:
void reverse(Node * & head){
Node * curr { head };
Node * prev { nullptr };
while(curr){
Node * next { curr->__Next__ };
curr->__Next__ = prev;
prev = curr;
curr = next;
}
return (void)(std::exchange(head, prev));
}
也有递归方法(需要注意的是新的头节点的维护):
Node * helper(Node *o){
if(! o || ! o->__Next__) return o;
Node * next = helper(o->__Next__);
o->__Next__->__Next__ = o;
(void)std::exchange(o->__Next__, nullptr);
return next;
}
template <class = void>
void reverse(Node * &head){
return (void)std::exchange(head, helper(head));
}
同时也有部分反转:
给定待反转的链表范围(用下标表示:[first, last),一个左闭右开区间)
void range_reverse(int32_t first, int32_t last, Node * & head){
if(! head || first * last < 0 || ! (first < last)) return;
Node * const dummy { new Node{ __Next__ : head, __Value__ : 0 } };
Node * sentinel { dummy };
for(int i {}; i < first; ++i) sentinel = sentinel->__Next__;
auto counter { last - first };
Node * current { sentinel->__Next__ };
Node * successor { nullptr };
while(counter --){
successor = current->__Next__;
current->__Next__ = successor->__Next__;
successor->__Next__ = sentinel->__Next__;
sentinel->__Next__ = successor;
}
head = dummy->__Next__;
delete dummy;
(void)std::exchange(dummy, nullptr);
}
stl中的<algorithm>::std::reverse(forwardIt first, forwardIt last, ...), 对list的特化版本的实现思路,就类似上述算法(当然list内部是双向环形链表,同时节点的分配和维护是allocator和forwardit,会复杂很多