python的链表操作_Python3单链表简单操作

单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。

class Node():

# 定义头结点

def __init__(self, data):

self.data = data

# 头指针为空

self.next = None

# 头插法

class SNode():

def __init__(self):

self.current_node = None

def add_node(self, data):

node = Node(data)

node.next = self.current_node

self.current_node = node

def append_node(self, data):

# 尾插法插入节点

node = Node(data)

cur = self.current_node

# 遍历链表直到头节点处停止遍历

while cur:

if cur.next == None:

break

cur = cur.next

cur.next = node

def travel(self):

'''

遍历链表

:return:

'''

cur = self.current_node

while cur:

print(cur.data)

cur = cur.next

def is_empty(self):

'''

判断链表非空

:return:

'''

return self.current_node == None

def get_lenth(self):

'''

获取链表的长度

:return:

'''

cur = self.current_node

count = 0

while cur:

count += 1

cur = cur.next

return count

def insert_node(self, index, data):

'''

指定位置插入节点

:param index:

:param data:

:return:

'''

link_len = self.get_lenth()

if index == 0:

self.add_node(data)

elif index >= link_len:

self.append_node(data)

else:

cur = self.current_node

for i in range(1, index):

cur = cur.next

node = Node(data)

node.next = cur.next

cur.next = node

def del_node(self, index):

'''

根据索引删除节点

:param index:

:return:

'''

# 找到前节点

cur = self.current_node

# 前驱节点

pre = None

count = 1

len_num = self.get_lenth()

while cur:

if index == 1:

self.current_node = cur.next

break

if count == index and count < len_num:

pre.next = cur.next

break

if count >= len_num:

pre.next = None

break

count += 1

pre = cur

cur = cur.next

if __name__ == "__main__":

test = SNode()

list_data = [1, 2, 3]

for i in list_data:

test.add_node(i)

test.travel()

# print(test.is_empty())

# print (test.get_lenth())

# test.append_node(4)

# test.insert_node(1, 4)

# test.travel()

# test.del_node(4)

# test.travel()

'''

单链表的操作

is_empty() 链表是否为空

length() 链表长度

travel() 遍历整个链表

add(item) 链表头部添加元素

append(item) 链表尾部添加元素

insert(pos, item) 指定位置添加元素

remove(item) 删除节点

search(item) 查找节点是否存在

'''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值