如何在java中合并未排序的链表

发布于 2025-01-13 11:40:19 字数 428 浏览 2 评论 0原文

// 我怎样才能实现这个功能?我想合并两个未排序的链表。

public static LinkedList mergeUnsortedLists(LinkedList list1, LinkedList list2) {
    LinkedList list3= new LinkedList();
    Node curr_odd = list1.head;
    Node curr_even = list2.head;
    Node prev = null;
    
    while(curr_odd != null){
        prev = curr_odd;
        curr_odd = curr_odd.getNext();
    
    }
    
    prev = curr_even;
    
  return list3;
}

// How can I make this function? I want to merge two unsorted linked list.

public static LinkedList mergeUnsortedLists(LinkedList list1, LinkedList list2) {
    LinkedList list3= new LinkedList();
    Node curr_odd = list1.head;
    Node curr_even = list2.head;
    Node prev = null;
    
    while(curr_odd != null){
        prev = curr_odd;
        curr_odd = curr_odd.getNext();
    
    }
    
    prev = curr_even;
    
  return list3;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请别遗忘我 2025-01-20 11:40:19
public static LinkedList mergeUnsortedLists(LinkedList list1, LinkedList list2) { 
    if (lis1.head == null) {
        return list2;
    }

    if (list2.head == null) {
        return list1;
    }

    for (Node crt = list1.head; crt.getNext() != null; crt = crt.getNext());
    
    // Need to link last element in l1 to head element of l2
    crt.setNext(list2.head);
    
    return list1;
}
public static LinkedList mergeUnsortedLists(LinkedList list1, LinkedList list2) { 
    if (lis1.head == null) {
        return list2;
    }

    if (list2.head == null) {
        return list1;
    }

    for (Node crt = list1.head; crt.getNext() != null; crt = crt.getNext());
    
    // Need to link last element in l1 to head element of l2
    crt.setNext(list2.head);
    
    return list1;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文