leetCode OJ 第二題

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

解析:把兩個逆序存儲的兩個數相加

完整代碼:

class ListNode(object):
	def __init__(self,x):
		self.val=x
		self.next=None
	def setVal(self,a,b):
		t=self
		t.next=ListNode(a)
		t=t.next
		t.next=ListNode(b)
		return self

class Solution(object):
	def addTwoNumbers(self,l1,l2):
 		h=ListNode(0)
		value=0
		p=h
		while l1 or l2:
			sum=value
			if l1:
				sum,l1=l1.val+sum,l1.next
			if l2:
				sum,l2=l2.val+sum,l2.next
			p.next=ListNode(sum%10)
			value=sum/10
			p=p.next
		p.next=ListNode(value)  if value else None
		return h.next

def start():
	l1=ListNode(2)
	l1.setVal(4,3)
	l2=ListNode(5)
	l2.setVal(6,4)
	add=Solution()
	l3=add.addTwoNumbers(l1,l2)
	while l3:
		print l3.val,
		l3=l3.next


發佈了31 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章