【Leetcode】Linked list

Sting  s="asd" //字符串双引号
char c='asd'   //字符单引号

Add Two Numbers

题目要求:
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

这道题其实是大数相加的处理,没什么难度,但需要注意以下几点:
1.因为存储是反过来的,即数字342存成2->4->3,所以要注意进位是向后的;
2.链表l1或l2为空时,直接返回,这是边界条件,省掉多余的操作;
3.链表l1和l2长度可能不同,因此要注意处理某个链表剩余的高位;
4. 两个数相加,可能会产生最高位的进位,因此要注意在完成以上1-3的操作后,判断进位是否为0,不为0则需要增加结点存储最高位的进位.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      int carry = 0;
    ListNode head = l1;
    ListNode prev = l1;
    while (l2 != null || carry != 0) {
        if (l1 == null) {
            l1 = new ListNode(0);
            prev.next = l1;
        }
        if (l2 != null) {
            l1.val += (l2.val + carry);
            l2 = l2.next;
        } else {
            l1.val += carry;
        }
        carry = l1.val / 10;
        l1.val %= 10;
        prev = l1;
        l1 = l1.next;
    }
    return head;
    }
}

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

思路:

Two lists are:
1->3->4->6
2->5->7->8

1) 1<2, current list: 1->(3)->4->6, other list: (2)->5->7->8
2) 3>2, current list: 1->2->(5)->7->8, other list: (3)->4->6
4) 5>3, current list: 1->2->3->(4)->6, other list: (5)->7->8
6) 4<5, current list: 1->2->3->4->(6), other list: (5)->7->8
7) 6>5, current list: 1->2->3->4->5->(7)->8, other list: (6)
8) 7>6, current list: 1->2->3->4->5->6->(), other list: (7)->8
9) combine current list with other list: 1->2->3->4->5->6->7->8

代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if(l1==null||l2==null) return l1==null?l2:l1;
    ListNode head = null;
    if(l1.val<=l2.val) {
        head=l1;
        l1=l1.next;
    }
    else {
        head=l2;
        l2=l2.next;
    }
    ListNode temp = head;
    while(l1!=null&&l2!=null){
        if(l1.val<=l2.val) {
            temp.next=l1;
            l1=l1.next;
        }
        else {
            temp.next=l2;
            l2=l2.next;
        };
        temp=temp.next;
    }
    temp.next=l1==null?l2:l1;
    return head;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值