链表的几个问题

2021-03-10  本文已影响0人  啊磊11

//链表两数相加->从头节点开始是个位依次为十百千

public static LinkedLISTsumLink(LinkedLIST heada, LinkedLIST headb){

LinkedLIST dummy =new LinkedLIST(-1,null);

    LinkedLIST curr = dummy;

    int carry =0;

    while (heada !=null || headb !=null || carry !=0){

int avalue = heada ==null?0:heada.value;

        int bvalue = headb ==null?0:headb.value;

        int k = (avalue + bvalue + carry)%10;

        carry =  (avalue + bvalue + carry)/10;

        LinkedLIST node =new LinkedLIST(k,null);

        curr.next = node;

        curr =curr.next;

        if(heada !=null){

heada = heada.next;

        }

if(headb !=null){

headb = headb.next;

        }

}

return dummy.next;

}

//删除链表的倒数第N个节点

public static LinkedLISTdeleteNodeN(LinkedLIST head,int N){

LinkedLIST dummy =new LinkedLIST(-1,null);

    dummy.next = head;

    LinkedLIST curr = dummy;

    LinkedLIST fast = head;

    int k =1;

    while (k<=N){

fast = fast.next;

    }

while (fast !=null){

fast = fast.next;

        curr = curr.next;

    }

curr.next = curr.next.next;

    return dummy.next;

}

//合并两个有序的链表

public static LinkedLISThebing(LinkedLIST heada, LinkedLIST headb){

if(heada ==null){

return  headb;

    }

if(headb ==null){

return  heada;

    }

if(heada.value

heada.next =hebing(heada.next,headb);

        return heada;

    }else {

headb.next =hebing(heada,headb.next);

        return  headb;

    }

}

//合并K个升序链表

public static LinkedLISThebingk(ArrayList lists){

if(lists.size() ==1){

return lists.get(0);

    }

if(lists.size() ==2){

return hebing(lists.get(0),lists.get(1));

    }else{

LinkedLIST atemp = lists.get(0);

        lists.remove(0);

        return hebing(atemp,hebingk(lists));

    }

}

//反转链表

public static LinkedLISTreverse(LinkedLIST heada){

if(heada ==null){

return null;

    }

LinkedLIST curr = heada;

    LinkedLIST pre =null;

    LinkedLIST next =null;

    while (curr !=null){

next = curr.next;

        curr.next = pre;

        pre = curr;

        curr = next;

    }

return  pre;

}

public static LinkedLISTreverse2(LinkedLIST head){

if(head ==null){

return head;

    }

LinkedLIST newhead =reverse2(head.next);

    head.next.next = head;

    head.next =null;

    return  newhead;

}

//反转前K个数莲表

public static LinkedLISTcurror =null;

public static LinkedLISTreversek(LinkedLIST head,int k){

if(k ==1){

curror = head.next;

      return head;

    }

LinkedLIST newhead =reversek(head.next,k-1);

    head.next.next = head;

    head.next =curror;

    return newhead;

}

//K个一组去反转链表

public static LinkedLISTreverseKgroup(LinkedLIST head, int k){

LinkedLIST curr = head;

    for(int i =0;i

curr = curr.next;

    }

LinkedLIST newhead =reversek(head, k);

    head.next =reverseKgroup(curr,k);

    return newhead;

}

上一篇下一篇

猜你喜欢

热点阅读