【剑指Offer】第6题-从尾到头打印链表-Python

LeetCode

对应的LeetCode题目如下:
206. 反转链表

解法一:栈

算法

首先遍历链表,遍历的顺序从头到尾,可输出的顺序却是从尾到头,这就是典型的后进先出,我们可以用栈实现。

每经过一个节点,把该节点放到栈中,遍历完之后再从栈顶开始输出。

code

   def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # nodes栈用来保存所有的节点值 
        nodes = []
        # p指向头结点
        p=head
        # 遍历保存所有val
        while p:
            nodes.append(p.val)
            p=p.next
        # x用来遍历赋值 y用来遍历记录值
        x=head
        num = len(nodes)
        while num:
            x.val = nodes.pop()
            x = x.next
            num = num - 1
        return head

解法二 递归

算法

【剑指Offer】第6题-从尾到头打印链表-Python
我们知道reverseList(head)返回输入的链表反转后的head,那么如果reverseList(head.next)的话

head
  1->2<-3<-4<-5
              |
             node

我们此时只需要head.next.next=head,也就是先建立一个双向连接

head
  1->2<-3<-4<-5
   <-         |
             node

然后再head.next=None,返回node即可。

      head
  null<-1<-2<-3<-4<-5
                    |
                   node

code

    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
                    return head
        node = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return node

解法三 三个指针

算法

很经典的问题,首先设置pre,cur,lat三个指针

pre   cur  lat
null   1 -> 2 -> 3 -> 4 -> 5 -> null

接着cur.next = pre

pre   cur  lat
null <-1    2 -> 3 -> 4 -> 5 -> null

接着pre = cur,cur = lat,lat = lat.next

      pre  cur  lat
null <-1    2 -> 3 -> 4 -> 5 -> null

重复上述操作直到lat=None

                     pre  cur  lat
null <-1 <- 2 <- 3 <- 4    5 -> null

最后cur.next = pre即可。

code

def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
	   if  head == None:
	            return None
	        pre = None
	        cur = head
	        lat = head.next

        while lat != None:
            cur.next = pre
            pre = cur
            cur = lat
            lat = lat.next

        cur.next = pre
        return cur 

相关文章:

  • 2021-12-30
  • 2022-12-23
  • 2021-06-17
  • 2021-09-09
  • 2021-12-28
  • 2021-05-01
  • 2021-08-11
  • 2022-02-13
猜你喜欢
  • 2021-10-10
  • 2022-12-23
  • 2021-12-13
  • 2021-11-23
  • 2021-05-22
  • 2021-10-29
相关资源
相似解决方案