• 题目要求:

image.png

  • 思路:

    • 定义一个新的head:myhead
    • 标记myhead的下一个点为mynext
    • 每次让myhead的next指向新的节点,新的节点的next指向mynext
    • 遍历链表直至链表为空
  • 核心代码:
#新建头节点
myhead = ListNode()
#标记头节点的next
mynext = myhead.next
#遍历链表当前的值为cur
cur = head
#下一个要插入到新链表的节点为cur.next
curnext = head.next

#当前节点不为空时:
while cur:
    #把当前遍历到的节点的next指向新的链表的mynext
    cur.next = mynext
    #新链表的头的next指向当前节点
    myhead.next = cur
    #更新mynext的值,因为每次插入是插入在新head后
    mynext = myhead.next
    #把cur的值更新为下一个要插入的节点
    cur = curnext
    #如果curnext不为空,curnext指向原链表的下一个节点
    if curnext:
        curnext = curnext.next
#返回新链表头的下一个节点
return myhead.next
  • 完整代码:

    • 加上条件判断给定链表是否为空
# 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
        """
        if head is None:
            return None
            
        myhead = ListNode()
        mynext = myhead.next
        cur = head
        curnext = head.next

        while cur:
            cur.next = mynext
            myhead.next = cur
            mynext = myhead.next
            cur = curnext
            if curnext:
                curnext = curnext.next
                
        return myhead.next

Adrianna
1 声望2 粉丝