Classic interview question - singly linked list reversal

struct node{
	node* next;
	T value;
};

Method One: General method

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;
}

Method Two: Recursive

  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;// 返回当前节点
 }

Reproduced in: https: //www.cnblogs.com/caleb/archive/2011/05/04/2036939.html

Guess you like

Origin blog.csdn.net/weixin_33832340/article/details/93174944