python实现反转部分单向链表

yipeiwu_com7年前Python基础

题目:

给定一个单链表的头指针 head, 以及两个整数 a 和 b,在单链表中反转 linked_list[a-b] 的结点,然后返回整个链表的头指针。
例如:
单链表[1000, 5, 12, 100, 45, ‘cecil', 999],
a = 4, b = 6,
返回的链表是[1000, 5, 12, 100, 999, ‘cecil', 45],也就是说,
a 和 b分别为索引值。如果a 和 b 超过了索引范围就返回错误。

代码:

我写的不够简洁,比较繁琐,但是能跑通,繁琐的原因在于我使用了 for 循环,对于 a == 0 的情况 for 循环无法识别。

  def reverse_part_linked_list(head, a, b): # 反转部分链表结点,a, b分别为索引值
    if head == 0:
      print "Empty linked list. No need to reverse."
      return head
    p = head
    length = 1
    while p != 0:
      length += 1
      p = p.next
    if length == 1:
      print "No need to reverse."
      return head
    if a < 0 or b > length-1 or a >= b:
      raise Exception("The given 'from' value and 'to' value is wrong.")
    p = head

    if a == 0: # 由于 for 循环中 xrange 的范围问题,我就分情况写了。
      tail, head = p, p
      pre = 0
      for _ in xrange(a, b+1):
        p = p.next
        head.next = pre
        pre = head
        head = p
      tail.next = p
      return head
    else:
      for _ in xrange(1, a):
        p = p.next
      front, tail, head = p, p, p
      p = p.next
      pre = 0
      for _ in xrange(a+1, b+2):
        p = p.next
        head.next = pre
        pre = head
        head = p
      front.next = pre
      tail.next = p
      return head

分析:

核心依然是反转链表的指针问题,均是一遍循环,时间复杂度o(n),空间复杂度为若干个变量。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现查找excel里某一列重复数据并且剔除后打印的方法

本文实例讲述了python实现查找excel里某一列重复数据并且剔除后打印的方法。分享给大家供大家参考。具体分析如下: 在python里面excel的简单读写操作我这里推荐使用xlrd(...

Python 中包/模块的 `import` 操作代码

用实例来说明 import 的作用吧。 创建以下包结构。一个文件夹 cookFish/,下面包含两个文件, __init__.py和cookBook.py。 为什么取这几个名字呢?假设我...

PyQT5 QTableView显示绑定数据的实例详解

PyQT5 QTableView显示绑定数据的实例详解

如下所示: import sys from PyQt5 import QtCore,QtGui from PyQt5.QtWidgets import QApplication,...

python中count函数简单用法

python中count函数的用法 Python count()方法 描述 Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。...

python执行CMD指令,并获取返回的方法

如下所示: result = os.popen('ps aux') res = result.read() for line in res.splitlines():...