双链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *reverse = NULL;
ListNode *temp=NULL ;
while(head)
{
//temp = head;
//reverse = temp;
//head = head->next;
//temp->next= head;
temp = head;
head = head ->next;
temp ->next= reverse;
reverse = temp;
}
return reverse;
}
};
用堆栈
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack <ListNode*> s;
ListNode *temp = NULL;
while(head)
{
s.push(head);
head=head->next;
}
if(s.empty()) return NULL;
temp=s.top();
s.pop();
head=temp;
while(!s.empty())
{
temp->next=s.top();
temp=temp->next;
s.pop();
}
temp->next=NULL;
return head;
}
};
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return r(head,NULL);
}
ListNode* r(ListNode* head,ListNode* newhead) {
if (!head) return newhead;
ListNode* next = head->next;
head->next = newhead;
return r(next, head);
}
};