删除链表中的中间节点和 a/b 处的结点 Python 版

来源:互联网 发布:数据交换共享 编辑:程序博客网 时间:2024/05/23 16:56

题目
给定一个链表的头结点 head,实现删除链表中的中间节点的函数。
例如:给定链表[1, 5, 12, 33, 45, 171, 999, 1001, 2000],删除结点 45,
给定链表[1, 5, 12, 33, 45, 171, 999, 1001],删除结点 33。
如果链表为空或长度为1,则不删除任何结点。
拓展:
给定一个链表的头结点 head,整数 a 和 b,实现删除链表中 a/b 处的结点。也就是说,head *a/b处的结点。

代码:

import mathclass LinkedListAlgorithms(object):    def __init__(self):        pass    def rm_mid_node(self, head):  # 给定一个链表,删除它的中间的一个结点,返回头指针        if head == 0:            return head        p = head        length = 1        while p != 0:            length += 1            p = p.next        if length == 1:            return head        mid = length / 2        for _ in xrange(1, mid-1):            head = head.next        head.next = head.next.next        return head    def rm_by_ratio(self, head, a, b):  # 给定一个链表,删除它按比例的 a/b处的一个结点,返回头指针        if a > b:            print "The given a should be lower than b."            return head        if head == 0:            return head        p = head        length = 1        while p != 0:            length += 1            p = p.next        if length == 1:            return head        ratio = length*float(a)/float(b)        for _ in xrange(1, int(math.ceil(ratio))-1):            head = head.next        head.next = head.next.next        return head

分析
核心还是删除一个链表的结点的操作,只是删除哪一个的问题,找到那一个就可以了。删除一个结点的函数我已经在线性链表的实现中写过了。

阅读全文
0 0
原创粉丝点击