zoukankan      html  css  js  c++  java
  • 链表的基本操作 三(增序链表的合并,无序链表的交集)

    #include<stdio.h>
    #include<malloc.h>


    typedef struct LinkNode{
    int data;
    struct LinkNode *next;
    }LinkNode;
    LinkNode *create_LNode(LinkNode *L){//创建链表,不带特殊头结点
    LinkNode *newp,*tail;
    int a;
    L=NULL;//创建一个不带头结点的链表
    printf("请输入节点: ");
    scanf("%d",&a);
    while(a!=-1){
    newp=(LinkNode*)malloc(sizeof(LinkNode));
    newp->next=NULL;
    newp->data=a;
    if(L==NULL){
    L=tail=newp;
    }
    else{
    tail->next=newp;tail=newp;
    }
    scanf("%d",&a);
    }
    return L;
    }


    LinkNode *LinkNode_Merge(LinkNode *La,LinkNode *Lb){//增序链表的合并,破坏La,Lb,组合Lc
    LinkNode *Lc,*pa,*pb,*tail;
    pa=La->next;
    pb=Lb->next;
    free(Lb);
    //Lc=tail=(LinkNode *)malloc(sizeof(LinkNode));
    Lc=tail=La;
    while(pa!=NULL&&pb!=NULL){
    if(pb->data<=pa->data){
    tail->next=pb;
    tail=pb;
    pb=pb->next;
    }
    else{
    tail->next=pa;
    tail=pa;
    pa=pa->next;
    }
    }
    if(pa!=NULL){
    tail->next=pa;
    }
    else{
    tail->next=pb;
    }
    return Lc;

    }


    LinkNode *LinkNode_Intersection(LinkNode *La,LinkNode *Lb){//无序链表LA交Lb
    LinkNode *Lc,*tail,*pa,*pb,*newp;
    Lc=NULL;//创建无头结点的Lc
    for(pa=La;pa;pa=pa->next){
    for(pb=Lb;pb;pb=pb->next){
    if(pb->data==pa->data){
    newp=(LinkNode *)malloc(sizeof(LinkNode));
    newp->data=pa->data;
    newp->next=NULL;
    if(Lc==NULL){
    Lc=newp;
    tail=newp;
    }
    else{
    tail->next=newp;
    tail=newp;
    }
    break;
    }
    }
    }
    return Lc;
    }


    void print(LinkNode *L){//输出函数
    LinkNode *p;
    for(p=L;p;p=p->next){
    printf("%d ",p->data);
    }
    printf(" ");
    }
    int main(){
    LinkNode *La,*Lb,*Lc;
    La=create_LNode(La);
    print(La);
    Lb=create_LNode(Lb);
    print(Lb);

    //Lc=LinkNode_Merge(La,Lb);//增序链表的合并
    Lc=LinkNode_Intersection(La,Lb);//无序链表的交集
    print(Lc);


    return 0;
    }

  • 相关阅读:
    C# 图片与Base64的相互转化
    LeetCode 303. Range Sum Query – Immutable
    LeetCode 300. Longest Increasing Subsequence
    LeetCode 292. Nim Game
    LeetCode 283. Move Zeroes
    LeetCode 279. Perfect Squares
    LeetCode 268. Missing Number
    LeetCode 264. Ugly Number II
    LeetCode 258. Add Digits
    LeetCode 257. Binary Tree Paths
  • 原文地址:https://www.cnblogs.com/jiafeng1996/p/11286101.html
Copyright © 2011-2022 走看看