标签:reader link 链表的操作 while public span 操作 leetcode read
本题主要是考查对链表的操作。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode cur1 = l1; ListNode cur2 = l2; int temp = 0; ListNode init = new ListNode(0); ListNode cur = init; while(cur1!=null || cur2!=null){ temp/=10; if(cur1!=null){ temp += cur1.val; cur1 = cur1.next; } if(cur2!=null){ temp += cur2.val; cur2 = cur2.next; } cur.next = new ListNode(temp%10); cur = cur.next; } if(temp/10!=0){ cur.next = new ListNode(1); } return init.next; } }
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: cur1 = l1 cur2 = l2 init = ListNode(0) cur = init temp = 0 while cur1 is not None or cur2 is not None: temp //= 10; if cur1 is not None: temp+=cur1.val cur1 = cur1.next if cur2 is not None: temp+=cur2.val cur2 = cur2.next cur.next = ListNode(temp%10) cur = cur.next if temp//10!=0: cur.next = ListNode(1) return init.next
标签:reader link 链表的操作 while public span 操作 leetcode read
原文地址:https://www.cnblogs.com/huangzengrui/p/12336143.html