标签:ret efi ima nbsp amp while 循环 http 链表 记录
一、题目
1、审题:
2、题意:
两个非空链表,加法运算,有进位的
二、解答:
1、分析:
用 while 循环进行判断,同时用标志 sign 记录每一次进位。注意两个链表可能不等长。
/** * 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) { int sign = 0, sum = 0; ListNode result = new ListNode(0); // 头结点 ListNode head = result; while(l1 != null && l2 != null) { sum = l1.val + l2.val + sign; sign = sum / 10; result.next = new ListNode(sum%10); result = result.next; l1 = l1.next; l2 = l2.next; } while(l1 != null) { sum = l1.val + sign; sign = sum / 10; result.next = new ListNode(sum%10); result = result.next; l1 = l1.next; } while(l2 != null) { sum = l2.val + sign; sign = sum / 10; result.next = new ListNode(sum%10); result = result.next; l2 = l2.next; } if(sign > 0) // 最后可能有进位 result.next = new ListNode(sign); return head.next; } }
标签:ret efi ima nbsp amp while 循环 http 链表 记录
原文地址:https://www.cnblogs.com/skillking/p/9352885.html