题目描述
输入一个链表,反转链表后,输出新链表的表头。
题目分析
链表的转置是一个很常见、很基础的数据结构题了,非递归的算法很简单,用三个临时指针 pre、head、next 在链表上循环一遍即可。递归算法也是比较简单的,但是如果思路不清晰估计一时半会儿也写不出来吧。
/*
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)
return pHead;
ListNode* pPre= NULL;
ListNode* pNext = NULL;
while(pHead != NULL)
{
pNext = pHead -> next; //暂存
pHead -> next = pPre;
pPre = pHead;
pHead = pNext;
}
return pPre;
}
};
递归实现:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL)
return pHead;
ListNode* newHead = ReverseList(pHead -> next);
pHead -> next ->next = pHead;
pHead ->next = NULL;
return newHead;
}
};