c++ 取两个链表的交集_使用C ++程序查找两个链表的交集

c++ 取两个链表的交集

Problem statement: Write a C++ program to find the intersection of two single linked lists.

问题陈述:编写一个C ++程序来查找两个单个链表的交集。

Example:

例:

    Let the first linked list be:
6->5->2->9->NULL
Let the second linked list to be:
2->7->NULL
So there intersection is:
2->NULL

Solution

Brute force approach:

蛮力法:

One technique can be to traverse all the nodes of a linked list and check whether the traversed node is in the other linked list or not. Such an approach takes O(m*n) times complexity. m, n=length of linked lists.

一种技术可以是遍历链表的所有节点,并检查遍历的节点是否在另一链表中。 这种方法需要O(m * n)乘以复杂度mn =链表的长度

Efficient approach:

高效的方法:

Efficient approach use to use merge sort.

高效的方法用于使用合并排序

  1. Sort both the linked list using merge sort. ( for detailed refer to: Merge sort for single linked lists)

    使用合并排序对两个链表进行排序。 (有关详细信息,请参阅: 合并单个链接列表的排序 )

  2. Scan each linked list and build intersection according to following:

    扫描每个链表并按照以下步骤建立交集:

  3. IF (list1->data < list2->data)
    No intersection found
    Traverse list1 by one step( list1=list1->next)
    ELSE IF(list1->data ==list2->data)
    Createnode(list1->data) && append node to the intersection list
    Traverse list1 by one step( list1=list1->next)
    Traverse list2 by one step( list2=list2->next)
    ELSE//list1->data >list2->data
    No intersection found
    Traverse list2 by one step( list2=list2->next)
    END IF-ELSE
    
    
  4. Display the intersection list

    显示路口清单

C ++实现查找两个链表的交集 (C++ implementation to find intersection of two linked lists)

#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data; // data field
struct node *next;
};
void display(class node* head){
node* current=head; // current node set to head
//traverse until current node isn't NULL
while(current!=NULL){ 
printf("%d ",current->data);
current=current->next; // go to next node
}
}
node* creatnode(int d){
node* temp=(node*)malloc(sizeof(node));
temp->data=d;
temp->next=NULL;
return temp;
}
//merging two sorted list 
node* mergeList(node* split1,node* split2){
node* newhead=NULL;
//base cases
if(split1==NULL)
return split2;
if(split2==NULL)
return split1;
if(split1->data<=split2->data){
newhead=split1;
newhead->next=mergeList(split1->next,split2);
}
else{
newhead=split2;
newhead->next=mergeList(split1,split2->next);
}
return newhead;
}
//split list for merge sort
void splitList(node* head,node** split1,node** split2){ 
node* slow=head;
node* fast=head->next;
while(fast!=NULL){
fast=fast->next;
if(fast!=NULL){
slow=slow->next;
fast=fast->next;
}
}
*split1=head;
*split2=slow->next;
//spliting
slow->next=NULL;
}
//merge sort
void mergeSort(node** refToHead){ 
node* head=*refToHead;
node* split1,*split2;
//base case
if(head==NULL || head->next==NULL){
return;
}
//split the list in two halves
splitList(head,&split1,&split2);
//recursively sort the two halves
mergeSort(&split1);
mergeSort(&split2);
*refToHead=mergeList(split1,split2);
return;
}
node* findIntersection(node* head1, node* head2){
//base case
if(head1==NULL && head2==NULL)
return NULL;
node* head4=NULL,*temp;
//for inserting the first common node
while( head1!=NULL && head2!=NULL && head4==NULL){ 
if(head1->data<head2->data){
head1=head1->next;
}
//intersection nodes(intersection)
else if(head1->data==head2->data){ 
head4=creatnode(head1->data);
temp=head4;
head1=head1->next;
head2=head2->next;
}
else{
head2=head2->next;
}
}
//for other common nodes(intersection)
while( head1!=NULL && head2!=NULL){ 
if(head1->data<head2->data){
head1=head1->next;
}
//intersection nodes
else if(head1->data==head2->data){ 
temp->next=creatnode(head1->data);
temp=temp->next;
head1=head1->next;
head2=head2->next;
}
else{
head2=head2->next;
}
}
return head4;
}
int main(){
printf("creating the linked list by inserting new nodes at the end\n");
printf("enter 0 to stop building the list, else enter any integer\n");
int k;
node* curr,*temp;
cout<<"enter list1...\n";
scanf("%d",&k);
node* head1=creatnode(k); //buliding list, first node
scanf("%d",&k);
temp=head1;
///inserting at the end//
while(k){
curr=creatnode(k);
temp->next=curr;//appending each node
temp=temp->next;
scanf("%d",&k);
}
cout<<"displaying list1...\n";
display(head1); // displaying the list
cout<<"\nenter list2...\n";
scanf("%d",&k);
node* head2=creatnode(k); //buliding list, first node
scanf("%d",&k);
temp=head2;
///inserting at the end//
while(k){
curr=creatnode(k);
temp->next=curr;//appending each node
temp=temp->next;
scanf("%d",&k);
}
cout<<"displaying list1...\n";
display(head2);
//sort both the lists
mergeSort(&head1);
mergeSort(&head2);
cout<<"\ndisplaying their intersection...\n";
node* head4=findIntersection(head1,head2);
if(head4)
display(head4);
else
cout<<"No intersection found\n";
return 0;
}

Output

输出量

First run:
creating the linked list by inserting new nodes at the end
enter 0 to stop building the list, else enter any integer
enter list1...
6 5 2 9 0
displaying list1...
6 5 2 9
enter list2...
2 7 0
displaying list1...
2 7
displaying their intersection...
2 
Second run:
creating the linked list by inserting new nodes at the end
enter 0 to stop building the list, else enter any integer
enter list1...
6 7 8 0
displaying list1...
6 7 8
enter list2...
1 5 2 0
displaying list1...
1 5 2
displaying their intersection...
No intersection found

Example with explanation:

带有说明的示例:

First linked list: 6->5->2->9->NULL
Second linked list: 2->7->NULL
After applying merge sort:
First linked list: 2->5->6->9->NULL
Second linked list: 2->7->NULL
------------------------------------------------------
//for better understanding nodes are represented 
//only by respective values
head1=2
head2=2
FindIntersection(2,2):
0th iteration
head1!=NULL && head2!=NULL
head1->data==head2->data //=2
thus head4(head of intersection list) =2
temp=head4=2
intersection list up to now:
2->NULL
head1=2->next=5;
head2=2->next=7;
1st iteration
head1!=NULL && head2!=NULL
head1->data<head2->data //5<7
thushead1=5->next=6;
temp=same as before
intersection list up to now:
2->NULL
head2=same as before;
2nd iteration
head1!=NULL && head2!=NULL
thushead1=6->next=9;
temp=same as before
intersection list up to now:
2->NULL
head2=same as before;
3rd iteration
head1!=NULL && head2!=NULL
head1->data>head2->data //9>7
thushead2=7->next=NULL;
temp=same as before
intersection list up to now:
2->NULL
Head1=same as before;
4th iteration
Head2=NULL
So, iteration stops & intersection list is build:
2->NULL

翻译自: https://www.includehelp.com/cpp-programs/find-intersection-of-two-linked-lists.aspx

c++ 取两个链表的交集

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/379935.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

只在IE中显示

只在IE中显示div{display:none;display:block;_display:block}转载于:https://www.cnblogs.com/lishenglyx/archive/2008/08/21/1273089.html

web安全---XSS漏洞之标签使用2

所有标签已经测试完并可以使用&#xff0c;测试环境&#xff1a;DVWA的反射型XSS&#xff0c;等级low 0x01 <script>标签 <script>alert(2)</script> <script>alert(2)</script//0x02 <img>标签 <img src"x" onerroralert(1)…

Java——多线程(铁路售票系统案例)

问题&#xff1a;铁路售票&#xff0c;一共100张&#xff0c;通过四个窗口卖完。 要求&#xff1a;分别用 继承Thread类 和 实现Runnable接口 去实现 ①用继承Thread类去实现 package com.yy.syn;public class Demo3_Ticket { /*** 铁路售票&#xff0c;一共100张&#xff…

Java LocalDateTime类| 带示例的getDayOfWeek()方法

LocalDateTime类getDayOfWeek()方法 (LocalDateTime Class getDayOfWeek() method) getDayOfWeek() method is available in java.time package. getDayOfWeek()方法在java.time包中可用。 getDayOfWeek() method is used to get the field value day-of-week that is an enum …

软件测试方法大汇总

软件测试方法大汇总 软件测试方法种类繁多&#xff0c;记忆起来混乱&#xff0c; 如果把软件测试方法进行分类, 就会清晰很多。 我参考一些书籍和网上的资料&#xff0c; 把常用的软件测试方法列出来&#xff0c; 让大家对软件测试行业有个总体的看法。 从测试设计方法分类 测试…

web安全----xss工具使用3

XSSer 0x01 安装 环境&#xff1a;kali、python3&#xff08;必须是python3&#xff0c;kali默认为python2&#xff09; 安装步骤&#xff1a; git clone https://github.com/epsylon/xsser.git cd xsser sudo python3 setup.py install 使用命令&#xff1a; xsser -h查看…

Java——多线程(死锁)

死锁是指&#xff1a;两个或两个以上的进程在执行过程中&#xff0c;由于竞争资源或者由于彼此通信而造成的一种阻塞的现象&#xff0c;若无外力作用&#xff0c;它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁&#xff0c;这些永远在互相等待的进程称为死锁进…

c# 前导0_C#| 用前导零填充整数

c# 前导0To pad an integer number with leading zero, we can use String.Format() method which is library method of String class in C#. 要用前导零填充整数&#xff0c;我们可以使用String.Format()方法&#xff0c;该方法是C&#xff03;中String类的库方法。 using S…

走到尽头的技术-MVC

MVC技术是一种WebApplication设计技术&#xff0c;相比于传统Web应用程序&#xff0c;MVC可以使程序结构更加清晰&#xff0c;他采用 Model&#xff0c;View&#xff0c;Controller 来管理和架构我们的Web资源&#xff0c;将不同的请求&#xff08;request&#xff09;导向不同…

Search Engine -垂直搜索小汇总

FilesTube: 共享文件搜索引擎,文件来自:Rapidshare, MegaUpload, Megashares, YouSendIt, SaveFile, FileFront和Badongo等很多文件储存网站,支持的文件格式包括:AVI, MP3, MPEG, MPG, RAR, WMA, WMV, EXE, ZIP等,主要为媒体格式,不支持中文 Picsearch:专业图片搜索引擎,中文界…

Java——多线程(线程安全问题)

同步为安全&#xff0c;不同步为不安全&#xff1b;也就是有synchronized这个标识符&#xff0c;就为线程安全&#xff0c;反之&#xff0c;为线程不安全。 ①Vector是线程安全的 ②StringBuffer是线程安全的 ③Hashtable是线程安全的 Collections.synchronized(xxx)&#…

web安全---XSS利用平台BLUE-LOTUS安装与使用

0x01 安装 环境&#xff1a;windows、phpstudy 下载地址&#xff1a;https://gitee.com/gid1314/BlueLotus_XSSReceiver-master 下载后将文件解压&#xff0c;重命名为blue&#xff0c;放在www目录下 访问&#xff1a;http://IP/blue 点击安装 这里只需要修改后台登陆密码和…

C#Convert.ToInt32(bool)方法-将bool值转换为int

C&#xff03;Convert.ToInt32(bool)方法 (C# Convert.ToInt32(bool) Method) Convert.ToInt32(bool) Method is used to convert a specific Boolean (bool) value to its equivalent integer (int 32 signed number). Convert.ToInt32(bool)方法用于将特定的布尔值(布尔值)转…

配置Microsoft Visual SourceSafe 2005的Internet访问

配置Microsoft Visual SourceSafe 2005的Internet访问 VSS2005发布以后&#xff0c;早就听说可以支持Internet访问&#xff0c;这是一个很有意思的特性。前两天有空&#xff0c;就安装配置了一下&#xff0c;成功访问。现在安装过程发布出来&#xff0c;大家共享。 步骤0&…

使用delphi 开发多层应用(十)安全访问服务器

前面讲了如何建立和访问服务器,但是前面建的服务器都没有安全控制&#xff0c;这里有很大的安全问题,第一是任何人做一个客户端都可以都可以访问 服务器。第二是数据在网络传输过程中都是明码的&#xff0c;没有加密&#xff0c;使用网络侦听器就可以检测到传输的内容。这是一个…

数组push()方法以及JavaScript中的示例

JavaScript push()方法 (JavaScript push() method) push() method is used adds/inserts an element at the end of an array, it returns nothing but changes the length of the array. push()方法用于在数组末尾添加/插入元素&#xff0c;它只返回改变数组的长度&#xff0…

C——整除的尾数

Problem Description 一个整数&#xff0c;只知道前几位&#xff0c;不知道末二位&#xff0c;被另一个整数除尽了&#xff0c;那么该数的末二位该是什么呢&#xff1f; Input 输入数据有若干组&#xff0c;每组数据包含二个整数a&#xff0c;b&#xff08;0< a<10000…

web安全---浏览器解析提交数据的过程

解码规则 html解析器对html文档进行解析&#xff0c;完成解析并创建DOM树JavaScript或者CSS解析器对内联脚本进行解析&#xff0c;完成js、css解码url解码会根据url所在的顺序不同而在JS解码或者解码后 解码顺序 html解析第一步执行&#xff0c;而JS解析和URL解析则要根据情…

commons-lang的FastDateFormat性能测试

commons-lang的FastDateFormat是一个thread-safe的&#xff0c;对SimpleDateFormat的一个重新实现。 SimpleDateFormat为什么不是thread-safe的呢&#xff1f;看一下具体实现就知道了&#xff0c;其父类中定义了成员变量Calendar&#xff0c;每次格式化日期时都会先重置这个Cal…

C——Flowers

Problem Description As you know, Gardon trid hard for his love-letter, and now he’s spending too much time on choosing flowers for Angel. When Gardon entered the flower shop, he was frightened and dazed by thousands kinds of flowers. “How can I choose!”…