python实现单向链表


#Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
nHead = ListNode(0)
carry = 0
head = nHead
flag = 0
while l1 or l2:
node = ListNode(flag)
print(node.val,node.next)
if l1:
node.val += l1.val
l1 = l1.next
if l2:
node.val += l2.val
l2 = l2.next
flag = node.val // 10
node.val %= 10
head.next, head = node, node
print(node.val,node.next,flag,head.val,head.next)
print(head.val,nHead.val,nHead.next.val,nHead.next.next.val)
return nHead.next
if __name__=="__main__":
nl = ListNode(0)
nl2 = ListNode(0)
l0 = nl
l1 = nl
list1=[5,8,6,7]
for x in list1:
node = ListNode(0)
node.val = x
l0.next=node
l0 = node
print (nl2.next,nl.next.next.val,nl.next.next.next.val,l1.next.next.next.next.val)

 

本来就对c中的链表不熟悉,做leetcode第二题直接看蒙,链表可以通过 listcode.val 访问当前值,通过listcode.next 指向下一个值的地址(类型还是listcode)

上一篇:oracle学习(1)


下一篇:BZOJ.2655.calc(DP/容斥 拉格朗日插值)