题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
解法一:原地旋转
### 解题思路
原地旋转链表,可以构建两个指针,一个指向当前结点的前一个,一个指向当前的结点,每次循环的时候,找到当前链表的下一个,在翻转的过程中,将当前结点指向前向结点,完成部分翻转,然后向后移动,更新当前结点,前向结点,直到反转完成。
### 代码
```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
"""
if not head:
return None
pre = None
cur = head
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
return pre
```
解法二:递归
# 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
"""
if head == None or head.next == None:
return head
tail = head.next
p = self.reverseList(head.next)
head.next = tail.next
tail.next = head
return p