美文网首页
python-反转链表

python-反转链表

作者: JerryLoveCoding | 来源:发表于2020-03-14 20:00 被阅读0次

    Leetcode定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

    第一种思路:
    初始指针i指向链表A头结点;
    初始指针j指向空,用于输出反向链表B;
    指针tempo指向一个临时的链表tempo,用于配合指针j。

    初始:
    指针i指向A的头结点,将头结点赋值给tempo节点,然后tempo链表的next链接指针j,也就是None。然后将tempo赋值给指针j;
    迭代:
    指针i向后遍历;将每次i指向的值赋值给指针tempo,tempo的next指向指针j;将tempo赋值给指针j。

    初始:
    i->1-2-3-4-5-6
    j->None
    循环:

    tempo->1
    tempo->1-None
    j->tempo
    i->i.next

    tempo->2
    tempo->2-1
    j->tempo
    i->i.next

    tempo->3
    tempo->3-2-1
    j->tempo
    i->i.next

    tempo->4
    tempo->4-3-2-1
    j->tempo
    i->i.next
    这是详细的迭代步骤看明白了吧。
    然后是代码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            i = head
            j = None
            while i:
                tempo = ListNode(i.val)
                tempo.next = j
                j = tempo
                i = i.next
            return j
    

    相关文章

      网友评论

          本文标题:python-反转链表

          本文链接:https://www.haomeiwen.com/subject/cyrnshtx.html