1. 题目描述
题目来源:力扣
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例1 输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例2 输入:head = [1,2] 输出:[2,1]
示例3 输入:head = [] 输出:[]
2. 题解
要注意这里输入的是一个链表里面的head,通过一直向下next,就能遍历整个链表。输入的head为自定义的ListNode类型。
思路如下:
图1. 反转链表
代码如下:
# 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
"""
# 首先按顺序将所有节点存储进列表
r = []
current = head
# 判断当前的node是不是空的,如果是空的,返回其自身即可
if current is None:
return current
while not current.next is None:
# 去除其next连接
r.append(ListNode(current.val))
current = current.next
r.append(current)
# 再将列表中元素重新组合成链表,逆序
r_tmp = list(reversed(r))
r = r_tmp[0]
current = r
for i in r_tmp[1:]:
current.next = i
current = current.next
return r
if __name__ == '__main__':
e1 = ListNode(1)
e2 = ListNode(2)
e3 = ListNode(3)
e4 = ListNode(4)
e5 = ListNode(5)
e1.next = e2
e2.next = e3
e3.next = e4
e4.next = e5
s = Solution()
r = s.reverseList(e1)
current = r
while not current.next is None:
print(current.val)
current = current.next
print(current.val)