(数据结构)在python下实现双向循环链表

  关于数据结构,我个人认为最最基础的就是你需要在C上进行学习以及实现,这样才能在别的语言上进行复现,唯一需要的就是给你一个相对正式的模版,了解一下大概的实现逻辑和流程。这里我记录一下我在python上复现双向循环链表的代码。

class ListNode:
    def __init__(self, data):
        self.data = data
        self.pre = None
        self.next = None


# This function is used to initiate the head node which is the
# head of the whole list
def ListInit():
    phead = ListNode(0)
    phead.pre = phead
    phead.next = phead
    return phead


def ListPrint(phead):
    cur = phead.next
    while cur != phead:
        print(cur.data, end=' ')
        cur = cur.next
    print('\n')


def ListPushBack(phead, pushback_value):
    tail = phead.pre
    node = ListNode(0)
    node.data = pushback_value
    node.next = phead
    phead.pre = node
    node.pre = tail
    tail.next = node


def ListPopBack(phead):
    if (phead.next == phead):
        return None
    else:
        tail = phead.pre
        pre_tail = tail.pre
        pre_tail.next = phead
        phead.pre = pre_tail
        del tail

def ListPushFront(phead, pushfront_value):
    cur = phead.next
    newnode = ListNode(pushfront_value)
    newnode.next = cur
    cur.pre = newnode
    newnode.pre = phead
    phead.next = newnode

def ListPopFront(phead):
    cur = phead.next
    next_cur = cur.next

    phead.next = next_cur
    next_cur.pre = phead
    del cur


def ListInsert(phead, insert_value, position = 0):
    cur = phead.next
    if position == 0:
        ListPopFront(phead, insert_value)
    else:
        for i in  range(0,position-1):
            cur = cur.next
        pre_cur = cur.pre
        newnode = ListNode(insert_value)
        newnode.next = cur
        cur.pre = newnode
        newnode.pre = pre_cur
        pre_cur.next = newnode




# test code
phead = ListInit()
ListPushBack(phead, 1)
ListPushBack(phead, 2)
ListPushBack(phead, 3)
ListPushBack(phead, 4)

ListPrint(phead)

ListPopBack(phead)
ListPopBack(phead)
ListPrint(phead)


ListPushFront(phead,2)
ListPushFront(phead,3)
ListPushFront(phead,4)
ListPrint(phead)

ListPopFront(phead)
ListPopFront(phead)
ListPopFront(phead)
ListPrint(phead)

ListPushFront(phead,3)
ListPushFront(phead,4)
ListPushFront(phead,5)
ListPrint(phead)


ListInsert(phead, 9, 3)
ListPrint(phead)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值