056-力扣刷题-206--反转链表

反转一个单链表。

示例:

输入: 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
# 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
        """
        pre = None
        cur = head
        while cur:
            nextcode = cur.next #先保存cur的下一个节点
            cur.next = pre #将cur执行的下一个节点进行反转
            pre = cur #让前一个指针执行当前的cur
            cur = nextcode #cur后移
        return pre #最后把pre的值返回,这个就是头结点