Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
- 思路1
自己想的,结果是超时,为什么会超时 >_<
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* next=NULL;
ListNode* nhead=head;
while(head && head->next)
{
next = head->next;
head->next = next->next;
nhead = next;
next->next = nhead;
}
return nhead;
}
};
- 思路2
创建一个新的头节点0,指向head
最后返回的时候直接用新的头节点的next
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre = new_head;
ListNode* cur = head;
while (cur && cur -> next) {
ListNode* temp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = temp;
}
return new_head -> next;
}
};
- 思路3
递归