并置两个链表

问题描述 投票:-1回答:1

编写一个concatenate()方法,该方法接受两个链接列表list1和list2,并将list2追加到list1的末尾。

例如,如果列表最初是:list1:

head-->3-->6-->7-->2-->null

list2:

head-->9-->5-->3-->null

列表1在连接后变为:

head-->3-->6-->7-->2-->9-->5-->3-->null

public static void concatenate(LinkedList list1, LinkedList list2) {
   //code


}
java linked-list singly-linked-list
1个回答
1
投票

想法:您需要一个指针来指向list1的头部。然后将指针移到list1的最后一个元素,并将其指定为指向list2头旁边的指针。

public class Node  
    { 
int data; 
Node next; 
Node(int d) {data = d; 
             next = null;} 
    } 



public static Node concatenate (Node head1, Node head2) //head1 points to head of list1, head2 points to head of list2
{
                Node temp=null;
                if (head1==NULL) //if the first linked list is empty
                                return (head2);
                if (head2==NULL) //if second linked list is empty
                                return (head1);

                temp=head1;       //place temporary pointer on the first node of the first linked list

                while (temp.next!=NULL) //move p to the last node
                                temp=temp.next;
                temp.next=head2;                           //address of the first node of the second linked list stored in the last node of the first linked list

                return (head1);
}
© www.soinside.com 2019 - 2024. All rights reserved.