算法通关村第2关【白银】| 两两交换链表结点、链表加法

1. 两两交换链表结点

算法通关村第2关【白银】| 两两交换链表结点、链表加法_第1张图片

 思路:参考链表反转,两两反转就可以了,每次往后预判两个结点

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null||head.next == null){
            return head;
        }
        ListNode vHead = new ListNode(-1);
        vHead.next = head;
        ListNode t = vHead;
        while(t.next != null && t.next.next != null){
            ListNode pre = t.next;
            ListNode cur = t.next.next;
            pre.next = cur.next;
            cur.next = pre;
            t.next = cur;
            t = pre;
        }
        return vHead.next;
    }
}

2.单链表加1

算法通关村第2关【白银】| 两两交换链表结点、链表加法_第2张图片 

思路:反转链表,从尾部开始加起,逢10进1,用变量carry记录。需要考虑99这种需要增加位数的值,当栈为空时还要判断当前需不需要进位即carry是否等于1,。同时还需要变量loop来控制值只加一次1。

public static ListNode plusOne(ListNode head){
        Stack stack = new Stack<>();
        while(head != null){
            stack.push(head.val);
            head = head.next;
        }
        int carry = 0;
        ListNode vHead = new ListNode(-1);
        int loop = 1;
        while(!stack.isEmpty() || carry > 0){
            int num =  stack.isEmpty() ? 0 : stack.pop();
            int sum = carry + num + loop;
            loop = 0;
            carry = sum == 10 ? 1 : 0;
            sum = sum % 10;
            ListNode cur = new ListNode(sum);
            cur.next = vHead.next;
            vHead.next = cur;
        }
        return vHead.next;
    }

3. 两数相加II

算法通关村第2关【白银】| 两两交换链表结点、链表加法_第3张图片

思路:和单链表加1相同的内核,核心仍是逢10进1,不同点在于不是只加一次,而是两个数相加,使用栈实现两个链表反转从尾部加起。同时需要注意将不需要相加的高位多余的数要拼接上去。

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack stack1 = new Stack<>();
        Stack stack2 = new Stack<>();
        while(l1 != null){
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while(l2 != null){
            stack2.push(l2.val);
            l2 = l2.next;
        }
        ListNode vHead = new ListNode(-1);
        int carry = 0;
        while((!stack1.isEmpty() && !stack2.isEmpty()) || carry > 0){
            int num1 = stack1.isEmpty() ? 0 : stack1.pop(); 
            int num2 = stack2.isEmpty() ? 0 : stack2.pop(); 
            int sum = carry + num1 + num2;
            carry = sum >= 10 ? 1 : 0;
            sum = sum % 10;
            ListNode cur = new ListNode(sum);
            cur.next = vHead.next;
            vHead.next = cur;
        }
        while(!stack1.isEmpty()){
            int sum = stack1.pop();
            ListNode cur = new ListNode(sum);
            cur.next = vHead.next;
            vHead.next = cur;
        }
        while(!stack2.isEmpty()){
            int sum = stack2.pop();
            ListNode cur = new ListNode(sum);
            cur.next = vHead.next;
            vHead.next = cur;
        }
        return vHead.next;
    }
}

你可能感兴趣的:(算法,算法,链表,数据结构)