📜  将一个链表插入另一个链表

📅  最后修改于: 2022-05-13 01:57:43.992000             🧑  作者: Mango

将一个链表插入另一个链表

给定两个链表, list1list2 ,大小分别为mn 。任务是list1的节点从第a节点删除到第b节点,并在它们的位置插入list2
例子

方法:可以使用对列表的简单迭代来解决任务。请按照以下步骤解决问题:

  • 开始迭代链表1 ,直到第一个节点
  • 现在这里取另一个变量并存储 list1 的第 (a+1)节点的地址,并将第一个节点链接到list2 ,然后遍历list2直到最后一个节点并停在那里
  • 第 (a+1)节点迭代到 list1 的第 b节点,然后将list2最后一个节点链接到 list1 的第(b+1) 个节点。
  • 返回list1头节点,然后打印整个 list1,这将是预期的输出。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
};
 
// Given a reference (pointer to pointer)
// to the head of a list and an int,
// appends a new node at the end
void append(Node** head_ref, int new_data)
{
    /* 1. allocate node */
    Node* new_node = new Node();
 
    Node* last = *head_ref; /* used in step 5*/
 
    /* 2. put in the data */
    new_node->data = new_data;
 
    /* 3. This new node is going to be
    the last node, so make next of
    it as NULL*/
    new_node->next = NULL;
 
    /* 4. If the Linked List is empty,
    then make the new node as head */
    if (*head_ref == NULL) {
        *head_ref = new_node;
        return;
    }
 
    /* 5. Else traverse till the last node */
    while (last->next != NULL) {
        last = last->next;
    }
 
    /* 6. Change the next of last node */
    last->next = new_node;
    return;
}
 
/* Given a reference (pointer to pointer)
 to the head of a list */
void mergeInBetween(Node** list1, Node** list2,
                    int a, int b)
{
    // keeping the index count
    int cnt = 0;
 
    // taking a new variable for
    // iterating over the linked list1
    Node* list = *list1;
    // condition for checking
    // till the count reached index a
    while (cnt + 1 != a) {
        // pointing the next node
        list = list->next;
        // increasing the count value everytime
        cnt++;
    }
    // Now demo will be used
    // to iterate from (a+1)th node
    // of list1 to bth node of list1
    Node* demo = list->next;
    // now we are linking
    // the ath node to the list2
    list->next = *list2;
    // now we use samp
    // for iterating over the list2
    Node* samp = *list2;
    // we go until the last node of the list2
    while (samp->next != NULL)
        samp = samp->next;
    // we go until the bth node of the list1
    while (cnt + 1 != b) {
        demo = demo->next;
        cnt++;
    }
    // now we simply link disconnected
    // parts of list1 and list2
    demo = demo->next;
    samp->next = demo;
}
 
// This function prints contents of
// linked list starting from head
void printList(Node* node)
{
    while (node != NULL) {
        cout << " " << node->data;
        node = node->next;
    }
}
 
/* Driver code*/
int main()
{
    Node *list1 = NULL, *list2 = NULL;
    append(&list1, 10);
    append(&list1, 11);
    append(&list1, 12);
    append(&list1, 13);
    append(&list1, 14);
    append(&list1, 15);
    append(&list2, 100);
    append(&list2, 101);
    append(&list2, 102);
    append(&list2, 103);
    int a = 3, b = 4;
    mergeInBetween(&list1, &list2, a, b);
    printList(list1);
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
 
class GFG{
 
static class Node {
    int data;
    Node next;
};
 
    // Given a reference (pointer to pointer)
    // to the head of a list and an int,
    // appends a new node at the end
static Node append(Node head_ref, int new_data)
{
    /* 1. allocate node */
    Node new_node = new Node();
 
    Node last = head_ref; /* used in step 5*/
 
    /* 2. put in the data */
    new_node.data = new_data;
 
    /* 3. This new node is going to be
    the last node, so make next of
    it as null*/
    new_node.next = null;
 
    /* 4. If the Linked List is empty,
    then make the new node as head */
    if (head_ref == null) {
        head_ref = new_node;
        return head_ref;
    }
 
    /* 5. Else traverse till the last node */
    while (last.next != null) {
        last = last.next;
    }
 
    /* 6. Change the next of last node */
    last.next = new_node;
    return head_ref;
}
 
    /*
     * Given a reference (pointer to pointer) to the head of a list
     */
static Node mergeInBetween(Node list1, Node list2,
                    int a, int b)
{
    // keeping the index count
    int cnt = 0;
 
    // taking a new variable for
    // iterating over the linked list1
    Node list = list1;
    // condition for checking
    // till the count reached index a
    while (cnt + 1 != a) {
        // pointing the next node
        list = list.next;
        // increasing the count value everytime
        cnt++;
    }
    // Now demo will be used
    // to iterate from (a+1)th node
    // of list1 to bth node of list1
    Node demo = list.next;
    // now we are linking
    // the ath node to the list2
    list.next = list2;
    // now we use samp
    // for iterating over the list2
    Node samp = list2;
    // we go until the last node of the list2
    while (samp.next != null)
        samp = samp.next;
    // we go until the bth node of the list1
    while (cnt + 1 != b) {
        demo = demo.next;
        cnt++;
    }
    // now we simply link disconnected
    // parts of list1 and list2
    demo = demo.next;
    samp.next = demo;
    return list1;
}
 
    // This function prints contents of
    // linked list starting from head
static void printList(Node node)
{
    while (node != null) {
        System.out.print(" " +  node.data);
        node = node.next;
    }
}
 
    /* Driver code */
public static void main(String[] args)
{
    Node list1 = null, list2 = null;
    list1= append(list1, 10);
    list1 = append(list1, 11);
    list1= append(list1, 12);
    list1 = append(list1, 13);
    list1 =append(list1, 14);
    list1 = append(list1, 15);
    list2 = append(list2, 100);
    list2 = append(list2, 101);
    list2 = append(list2, 102);
    list2 =append(list2, 103);
    int a = 3, b = 4;
    list1  = mergeInBetween(list1, list2, a, b);
    printList(list1);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python implementation of the above approach
class Node:
    def __init__(self):
        self.data = 0;
        self.next = None;
 
# Given a reference (pointer to pointer)
# to the head of a list and an int,
# appends a new Node at the end
def append(head_ref, new_data):
   
    ''' 1. allocate Node '''
    new_Node = Node();
 
    last = head_ref; ''' used in step 5 '''
 
    ''' 2. put in the data '''
    new_Node.data = new_data;
 
    '''
     * 3. This new Node is going to be the last Node, so make next of it as None
     '''
    new_Node.next = None;
 
    '''
     * 4. If the Linked List is empty, then make the new Node as head
     '''
    if (head_ref == None):
        head_ref = new_Node;
        return head_ref;
 
    ''' 5. Else traverse till the last Node '''
    while (last.next != None):
        last = last.next;
     
    ''' 6. Change the next of last Node '''
    last.next = new_Node;
    return head_ref;
 
'''
 * Given a reference (pointer to pointer) to the head of a list
 '''
def mergeInBetween(list1, list2, a, b):
   
    # keeping the index count
    cnt = 0;
 
    # taking a new variable for
    # iterating over the linked list1
    list = list1;
     
    # condition for checking
    # till the count reached index a
    while (cnt + 1 != a):
       
        # pointing the next Node
        list = list.next;
         
        # increasing the count value everytime
        cnt += 1;
     
    # Now demo will be used
    # to iterate from (a+1)th Node
    # of list1 to bth Node of list1
    demo = list.next;
     
    # now we are linking
    # the ath Node to the list2
    list.next = list2;
     
    # now we use samp
    # for iterating over the list2
    samp = list2;
     
    # we go until the last Node of the list2
    while (samp.next != None):
        samp = samp.next;
         
    # we go until the bth Node of the list1
    while (cnt + 1 != b):
        demo = demo.next;
        cnt+=1;
     
    # now we simply link disconnected
    # parts of list1 and list2
    demo = demo.next;
    samp.next = demo;
    return list1;
 
# This function prints contents of
# linked list starting from head
def printList(Node):
    while (Node != None):
        print(Node.data, end=" ");
        Node = Node.next;
 
''' Driver code '''
if __name__ == '__main__':
    list1 = None;
    list2 = None;
    list1 = append(list1, 10);
    list1 = append(list1, 11);
    list1 = append(list1, 12);
    list1 = append(list1, 13);
    list1 = append(list1, 14);
    list1 = append(list1, 15);
    list2 = append(list2, 100);
    list2 = append(list2, 101);
    list2 = append(list2, 102);
    list2 = append(list2, 103);
    a = 3
    b = 4;
    list1 = mergeInBetween(list1, list2, a, b);
    printList(list1);
 
# This code is contributed by gauravrajput1


C#
// C# implementation of the above approach
using System;
 
public class GFG{
 
  class Node {
    public int data;
    public Node next;
  };
 
  // Given a reference (pointer to pointer)
  // to the head of a list and an int,
  // appends a new node at the end
  static Node append(Node head_ref, int new_data)
  {
 
    /* 1. allocate node */
    Node new_node = new Node();
 
    Node last = head_ref; /* used in step 5*/
 
    /* 2. put in the data */
    new_node.data = new_data;
 
    /* 3. This new node is going to be
    the last node, so make next of
    it as null*/
    new_node.next = null;
 
    /* 4. If the Linked List is empty,
    then make the new node as head */
    if (head_ref == null) {
      head_ref = new_node;
      return head_ref;
    }
 
    /* 5. Else traverse till the last node */
    while (last.next != null) {
      last = last.next;
    }
 
    /* 6. Change the next of last node */
    last.next = new_node;
    return head_ref;
  }
 
  /*
     * Given a reference (pointer to pointer) to the head of a list
     */
  static Node mergeInBetween(Node list1, Node list2,
                             int a, int b)
  {
 
    // keeping the index count
    int cnt = 0;
 
    // taking a new variable for
    // iterating over the linked list1
    Node list = list1;
    // condition for checking
    // till the count reached index a
    while (cnt + 1 != a)
    {
 
      // pointing the next node
      list = list.next;
 
      // increasing the count value everytime
      cnt++;
    }
 
    // Now demo will be used
    // to iterate from (a+1)th node
    // of list1 to bth node of list1
    Node demo = list.next;
 
    // now we are linking
    // the ath node to the list2
    list.next = list2;
 
    // now we use samp
    // for iterating over the list2
    Node samp = list2;
 
    // we go until the last node of the list2
    while (samp.next != null)
      samp = samp.next;
 
    // we go until the bth node of the list1
    while (cnt + 1 != b) {
      demo = demo.next;
      cnt++;
    }
 
    // now we simply link disconnected
    // parts of list1 and list2
    demo = demo.next;
    samp.next = demo;
    return list1;
  }
 
  // This function prints contents of
  // linked list starting from head
  static void printList(Node node)
  {
    while (node != null) {
      Console.Write(" " +  node.data);
      node = node.next;
    }
  }
 
  /* Driver code */
  public static void Main(String[] args)
  {
    Node list1 = null, list2 = null;
    list1= append(list1, 10);
    list1 = append(list1, 11);
    list1= append(list1, 12);
    list1 = append(list1, 13);
    list1 = append(list1, 14);
    list1 = append(list1, 15);
    list2 = append(list2, 100);
    list2 = append(list2, 101);
    list2 = append(list2, 102);
    list2 = append(list2, 103);
    int a = 3, b = 4;
    list1  = mergeInBetween(list1, list2, a, b);
    printList(list1);
  }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
10 11 12 100 101 102 103 15

时间复杂度 O(m+n),n是list1的长度,m是list2的长度
辅助空间 O(1)