题目 reverse linked list
描述
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
解法
c++ 慢慢
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* curr = head;
ListNode* next = NULL;
ListNode* prev = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
python
class Solution:
def reverseList(self, head):
“”"
:type head: ListNode
:rtype: ListNode
“”"
curr = head
prev = None
next = None
while curr:
next = curr.next
curr.next=prev
prev = curr
curr = next
return prev