docker真的爽爆了 2022-08-21 00:50 采纳率: 66.7%
浏览 20
已结题

关于Java用链表实现减法的问题,如何解决?

Java用链表实现减法,咋判断是上第一个数比第二个数大还是第二个数比第一个数大,我判断过后,链表回不去了>︿<

    public Linkedlist sub(){
        Linkedlist res=new Linkedlist();Node head=new Node();Node pre=head;int ne=0;
        while (this.first.head!=null && this.second.head!=null) {
            if (compare()) {
                int ae=this.first.head.val-this.second.head.val-ne;
                if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}
                else{pre.next=new Node(ae);ne=0;}
                this.first.head=this.first.head.next;this.second.head=this.second.head.next;pre=pre.next;
            }
            else{
                int ae=-this.first.head.val+this.second.head.val-ne;if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}else{pre.next=new Node(ae);ne=0;}
                this.first.head=this.first.head.next;this.second.head=this.second.head.next;pre=pre.next;
            }
        }
        while (this.first.head==null && this.second.head!=null) {
            int ae=this.second.head.val-ne;if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}else{pre.next=new Node(ae);ne=0;}
            pre=pre.next;this.second.head=this.second.head.next;if (this.second.head==null) {pre.next=new Node('-');break;}
        }
        while (this.first.head!=null && this.second.head==null) {
            int ae=this.first.head.val-ne;if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}else{pre.next=new Node(ae);ne=0;}
            pre=pre.next;this.first.head=this.first.head.next;
        }
        if (ne==1) {pre.next=new Node('-');}
        return res;
    }
    public boolean compare(){
        Linkedlist te=this.first;Linkedlist de=this.second;
        while (te.head!=null && de.head!=null) {
            te.head=te.head.next;de.head=de.head.next;
        }
        if (te.head == null && de.head!=null) {return true;}
        else{return false;}
    //    if  else (this.first.head==null && this.second.head==null) {return false;}
        
    }

这是我的节点结构

class Node{
    Node next=null;
    int val;
    public Node(){}
    public Node(int val){
        this.val=val;
    }
    public Node(int val,Node next){
        this.val=val;this.next=next;
    }
}

展开全部

  • 写回答

0条回答 默认 最新

      编辑
      预览

      报告相同问题?

      问题事件

      • 系统已结题 8月28日
      • 创建了问题 8月21日
      手机看
      程序员都在用的中文IT技术交流社区

      程序员都在用的中文IT技术交流社区

      专业的中文 IT 技术社区,与千万技术人共成长

      专业的中文 IT 技术社区,与千万技术人共成长

      关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

      关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

      客服 返回
      顶部