Data structure and algorithm-singly linked list-exercise 3 (merge two ordered linked lists)

Topic: Merging two ordered singly linked lists, the linked list is still in order after the merge

1. Idea: To define a new head node, first compare the No. 1 node of the two linked lists, connect the smaller one, and then move it back, compare the size, and connect it. Sequentially to the end is empty.

The code is as follows (example):

 public HeroNode addtwolinkedlist(HeroNode head1, HeroNode head2) {
    
    
        //新链表的头结点
        HeroNode newhead = new HeroNode(0, "", "");
        if (head1.next == null) {
    
    
            return head2;
        }
        if (head2.next == null) {
    
    
            return head1;
        }
        if (head1.next == null && head2.next == null) {
    
    
            return null;
        }
        //设置链表一的临时指针
        HeroNode temp1 = head1.next;
        //设置链表二的临时指针
        HeroNode temp2 = head2.next;
        //设置新链表的临时指针
        HeroNode temp = newhead;
        while (temp1 != null && temp2 != null) {
    
    
            if (temp1.no < temp2.no) {
    
    
                temp.next = temp1;
                temp1 = temp1.next;
            } else if (temp1.no > temp2.no) {
    
    
                temp.next = temp2;
                temp2 = temp2.next;
            }
            temp = temp.next;
        }
        if (temp1==null){
    
    
            temp.next=temp2;
        }else {
    
    
            temp.next=temp1;
        }
        return newhead.next;
    }

2. Test the code

The code is as follows (example):

        HeroNode heroNode1 = new HeroNode(1, "林冲", "豹子头");
        HeroNode heroNode2 = new HeroNode(2, "花荣", "小李广");
        HeroNode heroNode3 = new HeroNode(3, "吴用", "智多星");
        HeroNode heroNode4 = new HeroNode(4, "武松", "行者");
        SingleLinkedList S1 = new SingleLinkedList();
        S1.addOrder(heroNode2);
        S1.addOrder(heroNode3);
        SingleLinkedList S2 = new SingleLinkedList();
        S2.addOrder(heroNode1);
        S2.addOrder(heroNode4);
        System.out.println("链表一为:");
        S1.list();
        System.out.println("链表二为:");
        S2.list();
        SingleLinkedList newsingleLinkedList = new SingleLinkedList();
        HeroNode newhead = newsingleLinkedList.addtwolinkedlist(S1.getHead(), S2.getHead());
        newsingleLinkedList.getHead().next= newhead;
        System.out.println("合并后的链表为");
        newsingleLinkedList.list();

to sum up

Draw a picture and clarify your ideas, only to jump out of a linked list and point the end of the new linked list to another node that is disconnected from the linked list.

Guess you like

Origin blog.csdn.net/slighting1128/article/details/111219530