欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

两个有序链表的合并(递归)

程序员文章站 2024-03-22 11:33:04
...

两个有序链表的合并(递归方式)

package com.dyg.list.test;
public class ListedMerge {
    //定义节点
    public static  class ListNode{
        int value;
        ListNode next;

        public ListNode(int value) {
            this.value = value;
        }
    }
    //合并2个有序链表
    //1.采用递归合并
    private static ListNode mergeListed(ListNode head1,ListNode head2){
        ListNode head = null;
        if (head1 == null && head2 !=null) {
            return head2;
        }
        if (head2 == null && head1 !=null) {
            return head1;
        }
        if (head1.value<head2.value) {
            head = head1;
            head.next = mergeListed(head1.next,head2);
        }else {
            head = head2;
            head.next = mergeListed(head2.next,head1);
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(5);
        ListNode node3 = new ListNode(7);
        node1.next = node2;
        node2.next = node3;
        node3.next = null;
        ListNode node4 = new ListNode(1);
        ListNode node5 = new ListNode(2);
        ListNode node6 = new ListNode(4);
        ListNode node7 = new ListNode(6);
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = null;
        ListNode head = mergeListed(node1, node4);
        while (head!=null){
            System.out.print("->"+head.value);
            head = head.next;
        }
    }
}

相关标签: 链表合并