148, adding two numbers II

Description Title:
given two non-empty list to represent two non-negative integer. The highest number of bits are located in the list starting position. They each node only stores a single digit. The two numbers together will return a new list.

You may assume that in addition to the numbers 0, these two figures will not begin with a zero.

Advanced:

If the input list can not be changed how to deal with? In other words, you can not flip nodes in the list.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
get a good time ah,
Code:

class Solution {
  	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode listNode1 = reverse(l1);
		ListNode listNode2 = reverse(l2);
		ListNode list1 = new ListNode(0);
		ListNode list2 = new ListNode(0);
		
		list1.next = listNode1;
		list2.next = listNode2;
		int jinwei = 0;
		while (list1.next != null && list2.next != null) {
			int tem = list1.next.val + list2.next.val + jinwei;
			list1.next.val = tem % 10;
			jinwei = tem / 10;
			list1 = list1.next;
			list2 = list2.next;
		}
		if(list1.next == null){
			list1.next = list2.next;
		}
		int tem = 0;
		while (list1.next != null) {
			tem = list1.next.val + jinwei;
			list1.next.val = tem % 10;
			jinwei = tem / 10;
			list1 = list1.next;
		}
		if(jinwei == 1){
			ListNode listNode = new ListNode(jinwei);
			list1.next = listNode;
			listNode.next = null;
		}
        return reverse(listNode1);
    } 
	public ListNode reverse(ListNode head){
		ListNode pre = null;
		while (head != null) {
			ListNode tem = head;
			head = head.next;
			tem.next = pre;
			pre = tem;
		}
		return pre;
	}
}

Of course, so to be, so do not flip the
two stacks to store

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        Stack<Integer> stack1=new Stack();
        Stack<Integer> stack2=new Stack();
        ListNode node1=l1;
        while(node1!=null){
            stack1.push(node1.val);
            node1=node1.next;
        }
        ListNode node2=l2;
        while(node2!=null){
            stack2.push(node2.val);
            node2=node2.next;
        }
        ListNode head=null;
        int flag=0;
        while(!stack1.isEmpty()||!stack2.isEmpty()||flag!=0){
            int value=0;
            if(!stack1.isEmpty())
                value+=stack1.pop();
            if(!stack2.isEmpty())
                value+=stack2.pop();
            value+=flag;
            ListNode node=new ListNode(value%10);
            flag=value/10;
            node.next=head;
            head=node;
        }
       return head;
    }
}


However, the speed of the first method is better;

Guess you like

Origin blog.csdn.net/qq_34446716/article/details/94743694