开发者社区> 问答> 正文

连接两个链接列表

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

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

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

}

问题来源:Stack Overflow

展开
收起
montos 2020-03-26 15:57:16 323 0
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);
    }
    

    回答来源:Stack Overflow

    2020-03-26 15:57:45
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载