Single chain reversal may be implemented by recursive, non-recursive and stack
List node definition:
struct ListNode{
int val;
Node* next;
ListNode(int x):val(x),next(nullptr){}
}
1, the stack
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)
return head;
stack<ListNode*>stk;
//将链表的结点全部压进栈
while(head){
stk.push(head);
head = head->next;
}
ListNode*cur,*nxt;
cur = nxt = stk.top();
stk.pop();
while(!stk.empty()){
nxt ->next = stk.top();
nxt = nxt ->next;
stk.pop();
}
//最后一个结点的next记得要指向nullptr
nxt ->next =nullptr;
return cur;
}
2, recursive
Recursive, until the last node in the list, with a pointer to the node, as the head node linked list after the inversion
in the recursive return procedure, so that the next node of the node to the node that \ ((head-> next -> the Next = head) \) ,
and let the node point \ (NULL \) . This realization reversal from the tail of a step by step list
Ps: pictures deleted from the network infringement
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode* ptr=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return ptr;
}
3, double pointer
Two nodes using intermediate node pointer and a pointer \ (TEMP (used to record the position of a node of the current node) \) , pointing to the current node and the previous node, the current node so that each cycle pointer field points to a node prior to
ListNode* reverseList(ListNode* head) {
ListNode* cur=head;
ListNode* pre=nullptr;
while(cur)
{
ListNode* tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}