链表的存储特点
链表的存储特点是:可以用任意一组存储单元来粗出单链表中的数据元素(存储单元可以是不连续的),而且除了存储每个数据元素
a
i
a_i
ai外,还必须存储指示其直接后继元素的信息。
注意:python中没有指针的概念,而类似指针的功能都是通过引用来实现的,而实现的代码中,都是通过引用来建立结点之间的联系。
如何实现链表逆序
给定一个带头结点的单链表,将其逆序。
即如果单链表原来为head->1->2->3->4->5->6->7
那么逆序后变成:head->7->6->5->4->3->2->1
方法一:就地逆序
主要思路:在遍历链表的时候,修改当前结点的指针域的指向,让其指向它的前驱结点。
# 方法一:就地逆序
class LNode:
def __init__(self, x=None):
self.data = x
self.next = None
def Reverse(head):
"""
parame:head 是链表头节点
方法功能: 对单链表进行逆序
"""
if head == None or head.next == None:
return
pre = head.next # 前驱结点
cur = pre.next # 当前结点
next_ = cur # 后继结点
pre.next = None # 没有这句话,就没有退出循环的条件。
# 把链表头结点变成尾结点
while cur.next != None:
next_ = cur.next
cur.next = pre
pre = cur
cur = next_
cur.next = pre
head.next = cur
def InputData():
head = LNode()
point = head
print("请输入数据,每输入一个结点数据就回车一次,直接回车就结束输入。")
data = input()
try:
data = eval(data)
except:
pass
while data!='':
node = LNode()
node.data = data
node.next = None
point.next = node
point = node
data = input()
try:
data = eval(data)
except:
pass
return head
def Output(head):
if head == None or head.next == None:
return
cur = head.next
cnt = 0
print("打印数据结果:")
while cur:
cnt += 1
print(cur.data, end='\t')
cur = cur.next
if cnt % 10 == 0:
print("\n")
print("\n")
if __name__ == "__main__":
head = InputData()
Output(head)
Reverse(head)
Output(head)
方法二:插入法
主要思路:从链表的第二个结点开始,把遍历到的结点插入到头结点的后面,直到遍历结束。
# 方法二:插入法
class LNode:
def __init__(self, x=None):
self.data = x
self.next = None
def Reverse1(head):
"""
parame:head 是链表头节点
方法功能:插入法,从链表的第二个结点开始,把遍历到的结点插入到头结点的后面,直到遍历结束
"""
if head is None or head.next is None:
return
cur = head.next.next
head.next.next = None
while cur is not None:
next_ = cur.next
cur.next = head.next
head.next = cur
cur = next_
def InputData():
head = LNode()
point = head
print("请输入数据,每输入一个结点数据就回车一次,直接回车就结束输入。")
data = input()
try:
data = eval(data)
except:
pass
while data!='':
node = LNode()
node.data = data
node.next = None
point.next = node
point = node
data = input()
try:
data = eval(data)
except:
pass
return head
def Output(head):
if head == None or head.next == None:
return
cur = head.next
cnt = 0
print("打印数据结果:")
while cur:
cnt += 1
print(cur.data, end='\t')
cur = cur.next
if cnt % 10 == 0:
print("\n")
print("\n")
if __name__ == "__main__":
head = InputData()
Output(head)
Reverse1(head)
Output(head)