445. Add Two Numbers II

让你求链表的和,这里有个follow up要求你不改变链表,那么可以使用stack,在这里我使用了三个stack两个用来存储值,一个用来存储node,发现跑出来的代码比别人慢了20ms左右,原来别人的第三个stack存的也是val,然后在pop过程中新建node。这里确实是一个优化的点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack1 = storeToStack(l1);
        Stack<Integer> stack2 = storeToStack(l2);
        int carry = 0;
        Stack<ListNode> stack = new Stack<ListNode>();
        while(!stack1.isEmpty()&&!stack2.isEmpty())
        {
            int val1 = stack1.pop();
            int val2 =stack2.pop() ;
            int remain = (val1+val2+carry)%10;
            carry =(val1+val2+carry)/10;
            ListNode temp = new ListNode (remain); 
            stack.push(temp);
            
        }
        if(!stack1.isEmpty())
        {
             while(!stack1.isEmpty())
             {
            int val1 = stack1.pop();
            int remain = (val1+carry)%10;
            carry =(val1+carry)/10;
            ListNode temp = new ListNode (remain); 
            stack.push(temp);
             }
        }
        if(!stack2.isEmpty())
        {
            while(!stack2.isEmpty())
            {
            int val2 =stack2.pop() ;
            int remain = (val2+carry)%10;
            carry =(val2+carry)/10;
            ListNode temp = new ListNode (remain); 
            stack.push(temp);
            }
            
        }
        if(carry==1)
        {
            ListNode temp = new ListNode (1); 
            stack.push(temp);
        }
        ListNode dummy = new ListNode (0);
        ListNode pos =dummy;
        while(!stack.isEmpty())
        {
            pos.next=stack.pop();
            pos=pos.next;
        }
        return dummy.next;
    }
    // return a stack stores the number of listnode
    private Stack<Integer> storeToStack(ListNode head)
    {
        Stack<Integer> stack = new Stack<>();
        while(head!=null)
        {
            stack.push(head.val);
            head=head.next;
        }
        return stack;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容