题意:反转一个单向链表
递归:
class Solution{
public:
ListNode *reverseList(ListNode *head){
if(head == NULL || head->next == NULL){
return head;
}
else{
ListNode *P = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return P;
}
}
};
非递归:
class Solution{
public:
ListNode *reverseList(ListNode *head){
if(head == NULL || head->next == NULL){
return head;
}
else{
ListNode *P = head;
ListNode *nextP = head->next;
head->next = NULL;
while(nextP){
ListNode *nnextP = nextP->next;
nextP->next = P;
P = nextP;
nextP = nnextP;
}
return P;
}
}
};