@@ -104,41 +104,54 @@ def reverse(self):
104104 prev = None
105105 current = self .head
106106 while current :
107- _next_node = current .next # 获取当前节点的下一个节点
108- current .next = prev # 当前节点指向前一个节点
109- prev = current # 前一个节点变成本节点
110- current = _next_node # 本节点变成下一个节点
107+ _temp = current .next # 对当前节点的下一个节点赋值
108+ current .next = prev # 反转当前节点的下一个节点指向前一节点
109+ prev = current # 前一个节点变成当前节点
110+ current = _temp # 节点偏移/迭代
111111 self .head = prev # 原来的链表头指向None
112112
113+ def __iter__ (self ):
114+ node = self .head
115+ while node :
116+ yield node .data
117+ node = node .next
118+
113119
114120def main ():
115- A = LinkedList ()
116- print ("Inserting 1st at Head" )
117- a1 = input ()
118- A .insert_head (a1 )
119- print ("Inserting 2nd at Head" )
120- a2 = input ()
121- A .insert_head (a2 )
122- print ("\n Print List : " )
123- A .show_node_data ()
124- print ("\n Inserting 1st at Tail" )
125- a3 = input ()
126- A .insert_tail (a3 )
127- print ("Inserting 2nd at Tail" )
128- a4 = input ()
129- A .insert_tail (a4 )
130- print ("\n Print List : " )
131- A .show_node_data ()
132- print ("\n Delete Head" )
133- A .delete_head ()
134- print ("Delete Tail" )
135- A .delete_tail ()
136- print ("\n Print List : " )
137- A .show_node_data ()
138- print ("\n Reverse Linked List" )
139- A .reverse ()
140- print ("\n Print List : " )
141- A .show_node_data ()
121+ link_list = LinkedList ()
122+ for i in range (10 ):
123+ link_list .insert_tail (i )
124+ link_list .show_node_data ()
125+ print ('=====reverse it======' )
126+ link_list .reverse ()
127+ link_list .show_node_data ()
128+ ########################
129+ # print("Inserting 1st at Head")
130+ # a1 = input()
131+ # link_list.insert_head(a1)
132+ # print("Inserting 2nd at Head")
133+ # a2 = input()
134+ # link_list.insert_head(a2)
135+ # print("\nPrint List : ")
136+ # link_list.show_node_data()
137+ # print("\nInserting 1st at Tail")
138+ # a3 = input()
139+ # link_list.insert_tail(a3)
140+ # print("Inserting 2nd at Tail")
141+ # a4 = input()
142+ # link_list.insert_tail(a4)
143+ # print("\nPrint List : ")
144+ # link_list.show_node_data()
145+ # print("\nDelete Head")
146+ # link_list.delete_head()
147+ # print("Delete Tail")
148+ # link_list.delete_tail()
149+ # print("\nPrint List : ")
150+ # link_list.show_node_data()
151+ # print("\nReverse Linked List")
152+ # link_list.reverse()
153+ # print("\nPrint List : ")
154+ # link_list.show_node_data()
142155
143156
144157if __name__ == '__main__' :
0 commit comments