1.什么是单链表
单链表是链表的一种,其特点是链表的连接方向是单向的,链表是非线性结构,在内存中存储数据是不连续的,单链表是由数据和指向下一个节点的指针组成,指针就是连接每一个节点的内存地址数据,链表在插入,删除一个节点的时候要比数组要快,在查找数据时比比数组慢,链表结构可以充分的利用内存空间,实现内存的动态内存管理
class Node():
def __init__(self,value):
self.value = value
self.next = None
class SingleLink():
def __init__(self):
self.header = None
self.length = 0
#判断链表是否为空
def is_empty(self):
if self.header == None:
return True
else:
return False
def add(self,node):
if self.is_empty():
self.header = node
else:
node.next = self.header
self.header = node
self.length += 1
def tail_add(self,node):
cur_node = self.header
if self.is_empty():
self.header = node
else:
while cur_node.next != None:
cur_node = cur_node.next
cur_node.next = node
self.length += 1
def travel(self):
cur_node = self.header
if self.is_empty():
print('当前链表为空')
else:
for i in range(self.length):
print(cur_node.value,end=' ')
cur_node = cur_node.next
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(3)
node5 = Node(4)
link1 = SingleLink()
link1.tail_add(node1)
link1.tail_add(node2)
link1.tail_add(node3)
link1.tail_add(node4)
link1.tail_add(node5)
link1.travel()
def reverse(head):
tmp = Node(0)
while head != None:
next = head.next
head.next = tmp.next
tmp.next = head
head = next
return tmp.next