Python 实现链表的定义
#! /bin/env/python
'''
# Python chainlist definition, reverse and add.
'''
import os
import sys
class Node:
# 节点定义
def __init__(self, data, pnext=None):
self.data = data
self.pnext = pnext
class Solution():
# n >=0
# 创建链表
def create_chain(self, n):
num = str(n)
list(num).reverse()
head_node = Node(num[0])
pre_node = head_node
for i in num[1:]:
cur_node = Node(i)
pre_node.pnext = cur_node
pre_node = cur_node
return head_node
# 打印链表
def show_chain(self, head_node):
if head_node == None:
print None
return
cur_node = head_node
sum = 0
count = 0
while cur_node.pnext != None:
count = count + 1
print cur_node, cur_node.data
sum = sum + int(cur_node.data) * 10**(count-1)
cur_node = cur_node.pnext
sum = sum + int(cur_node.data) *10**(count)
print cur_node, cur_node.data
print sum
return
# 反转链表
def reverse_chain(self, head_node):
if head_node == None:
return None
if head_node.pnext == None:
return head_node
# prepare the start model of loop
pre_node = head_node
mid_node = pre_node.pnext
pre_node.pnext = None
while mid_node.pnext != None:
next_node = mid_node.pnext
mid_node.pnext = pre_node
pre_node = mid_node
mid_node = next_node
mid_node.pnext = pre_node
return mid_node
# simulate add
# 两个链表相加
def add_2_chain(self, phead_1, phead_2):
if phead_1 == None:
return phead_2
if phead_2 == None:
return phead_1
l1 = phead_1
l2 = phead_2
init = Node(0)
head = init
print "BK1"
next_bit = 0
while l1 !=None or l2 != None:
print "&"
a = (0 if l1 == None else int(l1.data))
b = (0 if l2 == None else int(l2.data))
c = a + b + next_bit
if c >=10:
c = c - 10
next_bit = 1
print a,b,next_bit,c
head.pnext = Node(c)
head = head.pnext
try:
l1 = l1.pnext
except:
l1 = None
try:
l2 = l2.pnext
except:
l2 = None
if next_bit == 1:
head.pnext = Node(1)
return init.pnext
if __name__ == '__main__':
sol = Solution()
head1_node = sol.create_chain(9999999)
head2_node = sol.create_chain(1)
sol.show_chain(head1_node)
sol.show_chain(head2_node)
sum_head_node = sol.add_2_chain(head1_node, head2_node)
sol.show_chain(sum_head_node)
chain_2 = sol.reverse_chain(sum_head_node)
sol.show_chain(chain_2)