链表题--02----两数相加

Posted 高高for 循环

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表题--02----两数相加相关的知识,希望对你有一定的参考价值。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


两数相加

https://leetcode.com/problems/add-two-numbers/

题目:



方法1

分析 : 分成3个步骤

  1. 长链表L有,短链表s有
  2. 长链表L有,短链表s无
  3. 长链表L无,短链表s无

进位问题

    int carry = 0;
    while(l1 != null || l2 != null)      
            int sum = x + y + carry;            
            carry = sum / 10;
            sum = sum % 10;          
    

代码:

public class Code05_AddTwoNumbers 

	// 不要提交这个类
	public static class ListNode 
		public int val;
		public ListNode next;

		public ListNode(int val) 
			this.val = val;
		

		public ListNode(int val, ListNode next) 
			this.val = val;
			this.next = next;
		
	

	public static ListNode addTwoNumbers(ListNode head1, ListNode head2) 
		int len1 = listLength(head1);
		int len2 = listLength(head2);
		ListNode l = len1 >= len2 ? head1 : head2;
		ListNode s = l == head1 ? head2 : head1;
		ListNode curL = l;
		ListNode curS = s;
		ListNode last = curL;
		int carry = 0;
		int curNum = 0;
		while (curS != null) 
			curNum = curL.val + curS.val + carry;
			curL.val = (curNum % 10);
			carry = curNum / 10;
			last = curL;
			curL = curL.next;
			curS = curS.next;
		
		while (curL != null) 
			curNum = curL.val + carry;
			curL.val = (curNum % 10);
			carry = curNum / 10;
			last = curL;
			curL = curL.next;
		
		if (carry != 0) 
			last.next = new ListNode(1);
		
		return l;
	

	// 求链表长度
	public static int listLength(ListNode head) 
		int len = 0;
		while (head != null) 
			len++;
			head = head.next;
		
		return len;
	


方法2

分析:

将两个链表看成是相同长度的进行遍历,如果一个链表较短则在前面补 0,比如 987 + 23 = 987 + 023 = 1010









代码

  public ListNode addTwoNumbers(ListNode l1, ListNode l2) 
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;
        while(l1 != null || l2 != null) 
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;
            
            carry = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);

            cur = cur.next;
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        
        if(carry == 1) 
            cur.next = new ListNode(carry);
        
        return pre.next;
    

以上是关于链表题--02----两数相加的主要内容,如果未能解决你的问题,请参考以下文章

刷几道链表题,看看自己对指针的把握程度了

LeetCode 题号02: 两数相加

代码题(11)— 链表两数相加

02.两数相加

Leetcode 02: 两数相加(中等)

链表表示的两数相加