首页 > 其他 > 详细

【LeetCode每天一题】Reverse Linked List(链表反转)

时间:2019-03-23 17:16:15      阅读:179      评论:0      收藏:0      [点我收藏+]

Reverse a singly linked list.

Example:           Input: 1->2->3->4->5->NULL                   Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

解决思路:使用原地改变链表的指针进行反转。时间复杂度为O(n),空间复杂度为O(1). 流程图如下:

     技术分享图片

   

 1 class Solution(object):
 2     def reverseList(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: ListNode
 6         """
 7         pre = None   # 定义前驱节点
 8         cur = head   #  定义后驱节点
 9         while cur:     # 当cur为空时,循环结束
10             tem = cur.next       # 使用临时变量保存下一个节点
11             cur.next = pre       # 指向前驱节点
12             pre = cur            # 前驱节点复制到当前节点
13             cur = tem            # 临时变量进行复制
14         return pre

 

【LeetCode每天一题】Reverse Linked List(链表反转)

原文:https://www.cnblogs.com/GoodRnne/p/10584541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!