题目描述
输入一个链表,反转链表后,输出新链表的表头。
使用语言:C++(clang++3.9)
时间限制:< 1s
空间限制:< 32M
解题思路:
一.采用迭代的方法.
二.采用递归的方法.
迭代实现:
/*
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*returnNode = NULL;
ListNode* p = pHead;
while(p != NULL){
ListNode* tempNode = p->next;
p->next = returnNode;
returnNode = p;
p = tempNode;
}
return returnNode;
}
};
递归实现:
/*
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*returnNode = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return returnNode;
}
};
实验结果:
迭代:运行时间:3ms 占用内存:484k
递归:运行时间:4ms 占用内存:480k