# 数据结构-双向链表（Python实现）

## 双向链表

class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def getData(self):
return self.data

def setData(self, data):
self.data = data

def getNext(self):
return self.next

def getPrev(self):
return self.prev


class TwoWayList:
def __init__(self):
self.tail = None
self.length = 0


• 判断链表是否为空：
    def isEmpty(self):

• 在链表尾部添加节点：
    def append(self, item):
if self.length == 0:
node = Node(item)
self.tail = node
self.length = 1
return
node = Node(item)
tail = self.tail
tail.next = node
node.prev = tail
self.tail = node
self.length += 1


• 链表中插入节点：
    def insert(self, index, item):
length = self.length
if (index<0 and abs(index)>length) or (index>0 and index>=length):
return False
if index < 0:
index = index + length
if index == 0:
node = Node(item)
else:
self.tail = node
self.length += 1
return True
if index == length - 1:
return self.append(item)

for i in range(0, index):
node1 = node1.next
node2 = node1.next

node = Node(item)
node.prex = node1
node.next = node2
node1.next = node
node2.prev = node

self.length += 1
return True


• 根据节点数据获取链表上的节点
    def get(self, data):
for i in range(self.length):
if node.data == data:
return node
else:
node = node.next
else:
return False

• 根据下标获取链表上的节点
    def getByIndex(self, index):
if index >= self.length:
return False
if index == 0:

for i in range(self.length):
if i == index:
return now
now = now.next

• 更新指定下标节点的数据
    def setData(self, index, data):
if index >= self.length:
return False
if index == 0:

for i in range(self.length):
if i == index:
now.data = data
return True
now = now.next

• 删除指定下标的节点
    def remove(self, index):
if index >= self.length:
return False
if index == 0:
if self.length != 1:
self.length -= 1
return True
if index == self.length-1:
self.tail = self.tail.prev
self.tail.next = None
self.length -= 1
return True

for i in range(self.length):
if i == index:
now.next.prev = now.prev
now.prev.next = now.next
self.length -= 1
return True
now = now.next


• 链表翻转
    def reverse(self):
last = None
for i in range(self.length):
last = now
now = now.next
tmp = last.prev
last.prev = last.next
last.next = tmp
self.tail = tmp
return True


• 清空链表
    def clear(self):
self.tail = None
self.length = 0

• 实现链表类的__str__方法，定义print()函数打印链表的方式
    def __str__(self):
string = ''
for i in range(self.length):
string += str(node.data) + '/'
node = node.next
return string


li = TwoWayList()
li.isEmpty()
li.insert(0, 1)
li.getByIndex(0)
li.remove(0)

print(li)
li.append(1)

print(li)
li.append(2)
print(li)
li.append(4)
print(li)
li.insert(2,3)
print(li)
li.insert(3,4)

print(li)
li.remove(2)
print(li)
li.setData(2,10)
print(li)
li.reverse()
print(li)
print(li.get(2).data)
print(li.getByIndex(1).data)


posted @ 2019-07-15 23:58  目标进大厂的柳乘风  阅读(2639)  评论(0编辑  收藏  举报