定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
1
2
|
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
|
限制:
思路
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
pre = None
while cur:
after = cur.next
cur.next = pre
pre = cur
cur = after
return pre
def create_link(tmp):
head = None
cur = None
for i in tmp:
node = ListNode(i)
if head is None:
head = node
cur = head
else:
cur.next = node
cur = cur.next
return head
def traversal_link(head):
cur = head
while cur:
print(cur.val)
cur = cur.next
if __name__ == '__main__':
head = create_link([1, 2, 3, 4, 5])
# traversal_link(head)
solution = Solution()
cur = solution.reverseList(head)
traversal_link(cur)
|