今天真是吓死宝宝了
作为一个弱鸟菜鸟蜻蜓点水鸟,竟然今天AC出来个100%胜出,有点晕头转向=。=
206. Reverse Linked List
Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
也是得益于Discuss的启发。现在把我理解后自己写的代码展出:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *todo = NULL, *now = head, *pre = NULL;
while(now){
todo = now -> next;
now -> next = pre;
pre = now;
now = todo;
}
return pre;
}
};
写代码还是需要纸和笔
链表这东西,我在脑袋上都没搞清楚怎么翻转,那代码更不可能了。后来发现纸笔验算下还是可以的,说白了还是我的脑袋的内存不够,不够验算的~