struct node{node* next;T value;
};
方法一:常规方法
node* reverse(node*& head)
{if ( (head == Null) || (head->next == Null) ) return head;// 边界检测node* pNext = Null;node* pPrev = head;// 保存链表头节点node* pCur = head->next;// 获取当前节点while (pCur != Null){pNext = pCur->next;// 将下一个节点保存下来pCur->next = pPrev;// 将当前节点的下一节点置为前节点pPrev = pCur;// 将当前节点保存为前一节点pCur = pNext;// 将当前节点置为下一节点}head->next = NULL;head = pPrev; return head;
}
方法二:递归
node* reverse( node* pNode, node*& head){if ( (pNode == Null) || (pNode->next == Null) ) // 递归跳出条件{head = pNode; // 将链表切断,否则会形成回环return pNode;}node* temp = reserve(pNode->next, head);// 递归temp->next = pNode;// 将下一节点置为当前节点,既前置节点return pNode;// 返回当前节点}