Python实现单链表逆序
发布时间:2020-05-25 00:39:46 所属栏目:Python 来源:互联网
导读:Python实现单链表逆序
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 #!/usr/bin/env python
#-*- coding: utf-8 -*-
class Node(object):
def __init__(self,data,p=0):
self.data = data
self.next = p
class Reverse(object):
def __init__(self):
self.head = 0
def initlist(self):
print "input numbers here. '!' to quit"
try:
data = raw_input()
if data is not '!':
self.head = Node(int(data)) #指向第一个节点
p = self.head
while data != '!':
data = raw_input()
if data == '!':
break
else:
p.next = Node(int(data))
p = p.next
except ValueError:
print "input error!"
finally:
print "输入结束!"
def rever(self):
self.initlist()
p = self.head #指链表的第一个节点
nex = self.head.next
pre = Node(0) #设置一个空节点,让链表的头节点指向它
while self.head.next != 0:
nex = self.head.next
self.head.next = pre
pre = self.head
self.head = nex
self.head.next = pre
pre = self.head
###
#debug
print "逆序输出节点:t",while pre.next != 0:
print pre.data,pre = pre.next
###
if __name__ == '__main__':
#测试数据
#data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
l = Reverse()
l.rever()
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
