c language realizes the cross merge of two single linked lists
- 2020-06-23 01:28:51
- OfStack
As shown below:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
// Initialize the
Node *init()
{
Node *head=new Node;
head->next=NULL;
return head;
}
// A header creates a node
void insetList(Node *head,int i)
{
Node *cur=new Node;
cur->data=i;
cur->next=head->next;
head->next=cur;
}
// The list A,B generate
void CreateList(Node *head_A,Node *head_B)
{
for(int i=0;i<20;i++)
{
insetList(head_A,i);
i++;
insetList(head_B,i);
}
// Add list B The length of the
insetList(head_B,20);
insetList(head_B,25);
}
void Linklist(Node *head_A,Node *head_B,Node *List_C)
{
Node *pa=head_A->next; //pa Point to the list A The first node of
Node *pb=head_B->next; //pa Point to the list B The first node of
Node *pc=List_C; //pc Point to the C The head of the node
while(pa&&pb) // some 1 Exit at the end of traversal
{
pc->next=pa; // Put first A The nodes of the list
pc=pa; //pc Point to the pa . pc forward 1 A node
pa=pa->next; //pa forward 1 A node
pc->next=pb; // save B The nodes of the list
pc=pb;
pb=pb->next;
}
// Determine who ends first, and then link the remaining nodes that do not end
pc->next=pa?pa:pb;
delete head_B; // Release of the list B
}
// Print the list
void print(Node *head)
{
Node *temp=head->next; // Prevents the head pointer from moving
while(temp)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
void main()
{
Node *head_A=init(); // The list A
Node *head_B=init(); // The list B
Node *List_C=head_A; // The list C
// Create a list A . B
CreateList(head_A,head_B);
// Print the list
cout<<" The list A To: ";
print(head_A);
cout<<endl<<" The list B To: ";
print(head_B);
// Merge list A . B Generate the list C
Linklist(head_A,head_B,List_C);
cout<<endl<<" The list C To: "<<endl;
print(List_C);
system("pause");
}
Summary: The traversal of the linked list should be careful not to change the position of the pointer of the header at will. Three pointer of the structure should be declared for merging when merging. Note that the end of a 1 linked list should be linked and then release the generated linked list.