---
# System prepended metadata

title: 206-Reverse Linked List
tags: [Easy]

---

# 206-Reverse Linked List
###### tags: `Easy`

## Question
https://leetcode.com/problems/reverse-linked-list/
## Key
- 用過去、現在和未來三個指標，將未來節點數值改成現在節點數值、現在節點數值改成過去節點數值，再往下更新過去節點數值，再將現在節點指標轉向到未來節點，以此類推，直到最後一個節點

## Solution

### C++ direct iteration
```cpp=
ListNode* reverseList(ListNode* head) {
    ListNode* pre = NULL;
    ListNode* cur = head;
    while (cur != NULL)
    {
        ListNode *lat = cur->next;
        cur->next = pre;
        pre = cur;
        cur = lat;
    }
    return pre;
}

```
### C++ recursive
```cpp=
ListNode* reverseList(ListNode* head) {
    if(head == NULL || head->next == NULL){
        return head;
    }else{
        ListNode *h = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return h;
    }
}
```
### python
```python=
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = head
        current = None
        while pre != None:
            prec = current
            current = pre
            pre = pre.next
            current.next = prec
        return current
```