C语言求两个链表的交集

设A和B是两个单链表(带头节点),其中元素递增有序。设计一个算法从A和B中公共元素产生单链表C,要求不破坏A、B的节点。

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct LNode{
    int data;
    struct LNode *next;
}LNode, *LinkList;
//尾插法
void Insert(LinkList *L,int x)
{
    LNode* new_node = (LNode*)malloc(sizeof(LNode));
    new_node->data = x;
    new_node->next = NULL;
    LNode* cur = *L;
    while (cur->next != NULL) {
        cur = cur->next;
    }
    cur->next = new_node;
}
//创建带头节点的链表
LinkList CreateLinkList(){
    LinkList L = (LinkList)malloc(sizeof(LNode));
    L->next = NULL;
    return L;
}
//打印链表
void PrintLinkList(LinkList L)
{
    LNode* cur = L->next;
    printf("[");
    while (cur != NULL) {
        printf(" %d ",cur->data);
        cur = cur->next;
    }
    printf("]\n");
}
//头插法
void Push(LinkList* head,int data)
{
    LNode* new_node = (LNode*)malloc(sizeof(LNode));
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
}
//链表中有没有data啊?
bool isPresent(LNode *list,int data)
{
    while (list != NULL) {
        if(list->data == data){
            return true;
        }
        list = list->next;
    }
    return false;
}
//求两个链表的交集
LinkList GetIntersectionNode(LinkList A,LinkList B)
{
    LinkList result = (LinkList)malloc(sizeof(LNode));
    result->next = NULL;
    LNode* pA = A->next;
    LNode* pB = B->next;
    while (pA != NULL) {
        if(isPresent(pB, pA->data))
        {
            Insert(&result, pA->data);
        }
        pA = pA->next;
    }
    return result;
}
int main(int argc, const char * argv[]) {
    LinkList A = CreateLinkList();
    LinkList B = CreateLinkList();
    Insert(&A, 1);
    Insert(&A, 2);
    Insert(&A, 3);
    Insert(&A, 4);
    Insert(&A, 5);
    Insert(&A, 6);
    Insert(&A, 7);
    Insert(&A, 8);
    Insert(&A, 9);
    PrintLinkList(A);
    Insert(&B, 4);
    Insert(&B, 5);
    Insert(&B, 6);
    Insert(&B, 7);
    Insert(&B, 8);
    Insert(&B, 9);
    Insert(&B, 10);
    PrintLinkList(B);
    LinkList C = GetIntersectionNode(A,B);
    PrintLinkList(C);
    return 0;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值