关于数据结构,我个人认为最最基础的就是你需要在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)