题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路
使用递归实现:
/*
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* next = pHead->next;
pHead->next=NULL;
ListNode* newHead = ReverseList(next);
next->next = pHead;
return newHead;
}
};
使用迭代实现:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* newList = new ListNode(-1);
while(pHead!=NULL){
ListNode* next = pHead->next;
pHead->next=newList->next;
newList->next = pHead;
pHead=next;
}
return newList->next;
}
};