牛客网上有《剑指offer》的题目训练https://www.nowcoder.com/activity/oj
一个有关此题图文并茂的博客:http://blog.csdn.net/fx677588/article/details/72357389,有助于理解递归版的代码!!!
递归版本代码的参考网址:http://blog.csdn.net/yunzhongguwu005/article/details/10350339
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pReverseHead = NULL; //反序链表表头,初始化为空
ListNode* pNode = pHead; //当前结点
ListNode* pPrev = NULL; //原链表中当前结点的前一个结点,初始化为空
while(pNode != NULL){
ListNode* pNext = pNode->next;//原链表中当前结点的下一个结点
if(pNext == NULL)
pReverseHead = pNode; //若下一个结点为空,则该结点就是反序链表表头
pNode->next = pPrev;//原前一个结点变为当前结点的后继结点
pPrev = pNode;//当前结点变为前序结点
pNode = pNext;//当前结点更新
}
return pReverseHead;
}
};
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//如果链表为空或者链表中只有一个元素
if(pHead == NULL || pHead->next == NULL) //链表为空直接返回,而head->next为空是递归基
return pHead;
else {
ListNode* newhead = ReverseList(pHead->next);//先反转后面的链表
pHead->next->next = pHead;//再将当前节点设置为其然来后面节点的后续节点
pHead->next = NULL; //记得赋值NULL,防止链表错乱
return newhead; //新链表头永远指向的是原链表的链尾
}
}
};