编写一个concatenate((方法,该方法接受两个链表list1和list2,并将list2附加到list1的末尾。
例如,如果列表最初是:列表1:
head-->3-->6-->7-->2-->null
列表2:
head-->9-->5-->3-->null
list1在串联后变为:
head-->3-->6-->7-->2-->9-->5-->3-->null
public static void concatenate(LinkedList list1, LinkedList list2) {
//code
}
想法:您需要一个指针来指向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);
}