Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
咩。。。宝宝有预感又要超时了。。。
本来看成了数组。。。然后看到是链表。。。一脸懵逼。。。
然后。。。啊。。。把指针反过来。。。就好了。。。
hhhhhhh
/**
* 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* pre = NULL;
while (head) {
ListNode* next = head -> next;
head -> next = pre;
pre = head;
head = next;
}
return pre;
}
};
ok。。。