LeetCode之链表

2. 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.其中一个链表为空的情况;

2.链表长度相同时,且最后一个节点相加有进位的情况;

3.链表长度不等,短链表最后一位有进位的情况,且进位后长链表也有进位的情况;

/**
 * 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) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        int len1 = getLength(l1);
        int len2 = getLength(l2);
        ListNode head = null;
        ListNode plus = null;
        if(len1>=len2){
            head = l1;
            plus = l2;
        }else{
            head = l2;
            plus = l1;
        }
        ListNode p = head;
        int carry = 0;
        int sum = 0;
        while(plus!=null){
            sum = p.val + plus.val+carry;
            carry = sum/10;
            p.val = sum%10;
            if(p.next==null&&carry!=0){
                ListNode node = new ListNode(carry);
                p.next = node;
                carry = 0;
            }
            p = p.next;
            plus = plus.next;
        }
        while(p!=null&&carry!=0){
            sum = p.val+carry;
            carry = sum/10;
            p.val = sum%10;
            if(p.next==null&&carry!=0){
                ListNode node = new ListNode(carry);
                p.next = node;
                carry=0;
            }
            p = p.next;
        }
        return head;
    }
    
    public int getLength(ListNode l){
        if(l==null){
            return 0;
        }
        int len = 0;
        while(l!=null){
            ++len;
            l = l.next;
        }
        return len;
    }
}

 

 递归解法:


复杂度

时间O(n) 空间(n) 递归栈空间

思路

从末尾到首位,对每一位对齐相加即可。技巧在于如何处理不同长度的数字,以及进位和最高位的判断。这里对于不同长度的数字,我们通过将较短的数字补0来保证每一位都能相加。递归写法的思路比较直接,即判断该轮递归中两个ListNode是否为null。

  • 全部为null时,返回进位值
  • 有一个为null时,返回不为null的那个ListNode和进位相加的值
  • 都不为null时,返回 两个ListNode和进位相加的值
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return helper(l1,l2,0);
    }

    public ListNode helper(ListNode l1, ListNode l2, int carry){
        if(l1==null && l2==null){
            return carry == 0? null : new ListNode(carry);
        }
        if(l1==null && l2!=null){
            l1 = new ListNode(0);
        }
        if(l2==null && l1!=null){
            l2 = new ListNode(0);
        }
        int sum = l1.val + l2.val + carry;
        ListNode curr = new ListNode(sum % 10);
        curr.next = helper(l1.next, l2.next, sum / 10);
        return curr;
    }
}

迭代法:


复杂度

时间O(n) 空间(1)

思路

迭代写法相比之下更为晦涩,因为需要处理的分支较多,边界条件的组合比较复杂。过程同样是对齐相加,不足位补0。迭代终止条件是两个ListNode都为null。

注意

  • 迭代方法操作链表的时候要记得手动更新链表的指针到next
  • 迭代方法操作链表时可以使用一个dummy的头指针简化操作
  • 不可以在其中一个链表结束后直接将另一个链表串接至结果中,因为可能产生连锁进位
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        if(l1 == null && l2 == null){
            return dummyHead;
        }
        int sum = 0, carry = 0;
        ListNode curr = dummyHead;
        while(l1!=null || l2!=null){
            int num1 = l1 == null? 0 : l1.val;
            int num2 = l2 == null? 0 : l2.val;
            sum = num1 + num2 + carry;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            carry = sum / 10;
            l1 = l1 == null? null : l1.next;
            l2 = l2 == null? null : l2.next;
        }
        if(carry!=0){
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}

 

21. 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.

思路1:1)考虑特殊情况,两个链表至少有一个为空;

     2)考虑两个链表长度不一样的情况;

/**
 * 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)
            return l2;
        if(l2==null)
            return l1;
        
        ListNode head;
        if(l1.val<=l2.val){
            head = new ListNode(l1.val);
            l1 = l1.next;
        }else{
            head = new ListNode(l2.val);
            l2 = l2.next;
        }
        ListNode node = head;
        while(l1!=null&&l2!=null){
            if(l1.val<=l2.val){
                node.next = l1;
                node = node.next;
                l1 = l1.next;
            }else{
                node.next = l2;
                node = node.next;
                l2 = l2.next;
            }
        }
        if(l1!=null){
            node.next = l1;
        }
        if(l2!=null){
            node.next = l2;
        }
        return head;
    }
}

 

206. Reverse Linked List

Reverse a singly linked list.

 思路:1)首先判断头节点是否为空,为空则直接返回;

  2)

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null)
            return null;
        ListNode newHead = new ListNode(head.val);
        ListNode p = head.next;
        while(p!=null){
            ListNode node = new ListNode(p.val);
            node.next = newHead;
            p = p.next;
            newHead = node;
        }
        
        return newHead;
    }
}
sort-list

Sort a linked list in O(n log n) time using constant space complexity.

 思路:要求时间复杂度为O(nlogn),空间复杂度为O(1);

  1.考虑使用归并排序;

  2.归并排序需要找到中点,考虑使用快慢指针;

  3.归并中排序;

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null||head.next==null)
            return head;
        ListNode mid = getMid(head);
        ListNode right = sortList(mid.next);
        mid.next = null;
        ListNode left = sortList(head);
        return mergeList(left,right);
    }
    public ListNode getMid(ListNode head){
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast!=null&&fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow; 
    }
    
    public ListNode mergeList(ListNode left,ListNode right){
        if(left==null)
            return right;
        if(right==null)
            return left;
        ListNode head = null;
        if(left.val<=right.val){
            head = left;
            left = left.next;
        }else{
            head = right;
            right = right.next;
        }
        ListNode node = head;
        while(left!=null&&right!=null){
            if(left.val<=right.val){
                node.next = left;
                left = left.next;
            }else{
                node.next = right;
                right = right.next;
            }
            node = node.next;
        }
        if(left!=null){
            node.next = left;
        }
        if(right!=null){
            node.next = right;
        }
        return head;
    }
}
insertion-sort-list

Sort a linked list using insertion sort.

使用插入的方式对链表进行排序:

插入排序的思路如下:当前数与其前面的有序数依次进行比较,找到适当的位置插入,以此类推,得到最终结果;

此题的思路是:

  1)如果head为空或者head.next为空,则直接返回head;

  2)使用一个节点cur遍历当前待排序的节点,利用另一个节点pre从头开始遍历,若pre的值<=cur的值且两者不同,pre=pre.next;否则,记录第一个>cur的节点及其值,再遍历此节点到cur节点,调整节点值得位置,将cur的值交换到第一个>cur的节点处,直到链表遍历完;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode cur = head;
        while(cur!=null){
            ListNode pre = head;
            while(pre.val<=cur.val&&pre!=cur){
                pre = pre.next;
            }
            int firstVal = pre.val;
            ListNode mark = pre;
            while(pre!=cur){
                int nextVal = pre.next.val;
                int tmp = nextVal;
                pre.next.val = firstVal;
                firstVal = tmp;
                pre = pre.next;
            }
            mark.val = firstVal;
            cur = cur.next;
        }
        return head;
    }
}
 
reorder-list
Given a singly linked list LL0→L1→…→Ln-1→Ln,

reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.

解题思路:

  先使用快慢指针找到链表的中点,反转后半部分的链表,再以中点为断点进行前后两部分交叉合并;

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head==null||head.next==null)
            return;
        ListNode fast = head.next;
        ListNode slow = head;
        while(fast!=null&&fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode pre = reverseList(slow.next);
        slow.next = pre;
        ListNode p = head;
        ListNode q = slow.next;
        while(q!=null&&p!=null){
            slow.next = q.next;
            q.next = p.next;
            p.next = q;
            p = q.next;
            q = slow.next;
        }
    }
  //反转单链表
public ListNode reverseList(ListNode head){ if(head==null||head.next==null) return head; ListNode cur = head.next; ListNode pre = head; while(cur!=null){ ListNode node = cur.next; cur.next = pre; pre = cur; cur = node; } head.next = cur; return pre; } }

 

转载于:https://www.cnblogs.com/coffy/p/5731230.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Rust 是一种现代的编程语言,特别适合处理内存安全和线程安全的代码。在 LeetCode 中,链表是经常出现的题目练习类型,Rust 语言也是一种非常适合处理链表的语言。接下来,本文将从 Rust 语言的特点、链表的定义和操作,以及 Rust 在 LeetCode链表题目的练习等几个方面进行介绍和讲解。 Rust 语言的特点: Rust 是一种现代化的高性能、系统级、功能强大的编程语言,旨在提高软件的可靠性和安全性。Rust 语言具有如下几个特点: 1. 内存安全性:Rust 语言支持内存安全性和原语级的并发,可以有效地预防内存泄漏,空悬指针以及数据竞争等问题,保证程序的稳定性和可靠性。 2. 高性能:Rust 语言采用了“零成本抽象化”的设计思想,具有 C/C++ 等传统高性能语言的速度和效率。 3. 静态类型检查:Rust 语言支持静态类型检查,可以在编译时检查类型错误,避免一些运行时错误。 链表的定义和操作: 链表是一种数据结构,由一个个节点组成,每个节点保存着数据,并指向下一个节点。链表的定义和操作如下: 1. 定义:链表是由节点组成的数据结构,每个节点包含一个数据元素和一个指向下一个节点的指针。 2. 操作:链表的常用操作包括插入、删除、查找等,其中,插入操作主要包括在链表首尾插入节点和在指定位置插入节点等,删除操作主要包括删除链表首尾节点和删除指定位置节点等,查找操作主要包括根据数据元素查找节点和根据指针查找节点等。 Rust 在 LeetCode链表题目的练习: 在 LeetCode 中,链表是常见的题目类型,而 Rust 语言也是一个非常适合练习链表题目的语言。在 Rust 中,我们可以定义结构体表示链表的节点,使用指针表示节点的指向关系,然后实现各种操作函数来处理链表操作。 例如,针对 LeetCode 中的链表题目,我们可以用 Rust 语言来编写解法,例如,反转链表,合并两个有序链表,删除链表中的重复元素等等,这样可以更好地熟悉 Rust 语言的使用和链表的操作,提高算法和编程能力。 总之,在 Rust 中处理链表是非常方便和高效的,而 LeetCode 中的练习也是一个非常好的机会,让我们更好地掌握 Rust 语言和链表数据结构的知识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值