LeetCode-----2023/7/3--------两数相加(链表和栈)

官方解法

使用栈

    链表中的数位的顺序与我们进行相加的顺序是相反的,为了逆序处理所有数位,可以利用栈。

 

import javax.xml.soap.Node;
//定义链表节点
public class ListNode {
	int val;
    ListNode next;

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

package Day20230703;
//定义链表
public class LinkedList {
	 ListNode head; // 头节点

	    LinkedList() {
	        this.head = null;
	    }

	    // 在链表末尾添加新节点,尾插法
	    void addNode(int val) {
	        ListNode newNode = new ListNode(val);

	        if (head == null) {
	            head = newNode;
	        } else {
	            ListNode current = head;
	            while (current.next != null) {
	                current = current.next;
	            }
	            current.next = newNode;
	        }
	    }
	    // 打印链表节点的值
	    void printList() {
	        ListNode current = head;
	        System.out.print("链表节点的值:");

	        while (current != null) {
	            System.out.print(current.val + " ");
	            current = current.next;
	        }

	        System.out.println();
	    }
}
package Day20230703;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
import java.util.Stack;

import javax.xml.soap.Node;

public class AddTwoNum {
	public static void main(String[] args) {
		LinkedList l1 = new LinkedList();
		LinkedList l2 = new LinkedList();
		l1.addNode(7);
		l1.addNode(2);
		l1.addNode(4);
		l1.addNode(3);
		l2.addNode(5);
		l2.addNode(6);
		l2.addNode(4);//这里也可以写while循环来进行创建链表操作
		LinkedList l3 = addTwoNum(l1, l2);
		l3.printList();
		
	}
	public static LinkedList addTwoNum(LinkedList l1,LinkedList l2) {
//		Stack<Integer> stack1 = new Stack<Integer>();
//		Stack<Integer> stack2 = new Stack<Integer>();
		   Deque<Integer> s1 = new ArrayDeque<Integer>();
		   Deque<Integer> s2 = new ArrayDeque<Integer>();
		   ListNode p = l1.head;
		while (p!=null) {
			
			s1.push(p.val);
			p=p.next;
			
			
			
		}
		ListNode q = l2.head;
		while (q!=null) {
			
			s2.push(q.val);
			q=q.next;
			
			
		}
		int carry = 0;
		LinkedList l3 = new LinkedList();
		while (!s1.isEmpty()||!s2.isEmpty()||carry!=0) {
			 	int a = s1.isEmpty() ? 0 : s1.pop();

	            int b = s2.isEmpty() ? 0 : s2.pop();

//	            if (!s1.isEmpty()) s1.pop();//出栈操作
//	            if (!s2.isEmpty()) s2.pop();
	            int cur = a + b + carry;
	         
			carry = cur/10;
			cur = cur%10;
			   ListNode newNode = new ListNode(cur);
//			if (l3.head==null) {
//				l3.head = newNode;
//			}
//			else {
//				newNode.next = l3.head;
//			}
			   newNode.next=l3.head;
			   l3.head=newNode;
	
			
		}
		return l3;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值