面试经常会考的题,先来看C++:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* NewH = NULL;
while(cur!=NULL){
ListNode* tmp = cur->next;
cur->next = NewH;
NewH = cur;
cur = tmp;
}
return NewH;
}
};
python可以同时赋值,所以不需要临时指针:
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur,prev = head,None
while cur:
cur.next,prev,cur = prev,cur,cur.next
return prev