zoukankan      html  css  js  c++  java
  • leetcode 链表相关

    1.给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

    如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

    您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

    示例:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807


    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
    int x = (p != null) ? p.val : 0;
    int y = (q != null) ? q.val : 0;
    int sum = carry + x + y;
    carry = sum / 10;
    curr.next = new ListNode(sum % 10);
    curr = curr.next;
    if (p != null) {
    p = p.next;
    }

    if (q != null) {
    q = q.next;
    }
    }
    if (carry > 0) {
    curr.next = new ListNode(carry);
    }
    return dummyHead.next;
    }

    public static void main(String[] args) {
    Solution solution = new Solution();
    ListNode node1 = solution.arrToList(new int[]{2, 4, 3});
    ListNode node2 = solution.arrToList(new int[]{5, 6, 4});
    ListNode result = solution.addTwoNumbers(node1, node2);
    System.out.println(result);
    }

    public ListNode arrToList(int[] arr){
    //用于存放数组转成的链表
    ListNode result = null;
    //指向result的指针
    ListNode p = null;
    for (int i = 0; i < arr.length; i++){
    //如果为null,则存放为头节点
    if (result == null){
    p = new ListNode(arr[i]);
    result = p;
    } else {
    //next指向下一个节点
    p.next = new ListNode(arr[i]);
    p = p.next;
    }
    }
    return result;
    }

    }

    class ListNode{
    int val;
    ListNode next;

    ListNode(int val) {
    this.val = val;
    }
    }

    2.
    将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4
    
    
    ListNode dummyHead = new ListNode(0);
    ListNode cur = dummyHead;
    while (l1 != null && l2 != null) {
    if (l1.val < l2.val) {
    cur.next = l1;
    cur = cur.next;
    l1 = l1.next;
    } else {
    cur.next = l2;
    cur = cur.next;
    l2 = l2.next;
    }
    }

    if (l1 == null) {
    cur.next = l2;
    } else {
    cur.next = l1;
    }

    return dummyHead.next;
  • 相关阅读:
    取出某块内存的二进制数据
    拷贝构造函数的第一个参数必须是自身类类型的引用
    大小端,memcpy和构造函数
    类型装换和内存数据显示
    ERROR: iterator not incrementable || iterator not decrementable
    什么时候删除指针后,要给指针赋NULL
    chapter11、4concurrent.future模块
    chapter11、3多进程 multiprocessing
    chapter8.3、二分查找
    chapter8.2、面向对象三要素--继承
  • 原文地址:https://www.cnblogs.com/cr1719/p/10362219.html
Copyright © 2011-2022 走看看