连接两个链表
Concatenate Two Linked Lists
编写一个 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);
}
编写一个 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);
}