【练习】c++单向链表求交集

思路:先递增排序再二路归并

在这里插入图片描述
代码:

//直接插入排序
void sort(node*& L) {
    node* p = L->next->next;
  
    node* q;
    L->next->next = NULL;//构建只含一个数据结点的有序表
    node* pre = L;
    while (p != NULL) {
        pre = L;//注意每次最外面的while中都要初始化pre
        q = p->next;//q保存当前p结点的后继结点
        while (pre->next != NULL && pre->next->data < p->data)
            pre = pre->next;
        p->next = pre->next;//当pre->next->data>p->d%ata 在pre后面插入p结点 因为p的数据更小 按递增排序
        pre->next = p;
        p = q;//p指向原来的后继结点
    }
}

void jiao(node* a, node* b, node*& c) {
    
    node* pa = a->next, * pb = b->next;
    node* s, * r;
    c = new node;
 //   c->next = NULL;
    r = c;
    while (pa != NULL && pb != NULL) {
       
        if (pa->data == pb->data) {
            s = new node;
            s->data = pa->data;
            s->next = c->next;
            c->next = s;
            pa = pa->next;
            pb = pb->next;
        }
        else if (pb->data < pa->data) {
            pb = pb->next;
        }
        else {
            pa = pa->next;
            
        }
    }

}

int main()
{
    srand(0);
    node* begin=new node;
    begin->next = NULL;
    node* m = new node;

    m->data = rand() % 15;
    //cout << m->data;
      m->next= begin->next;
      begin->next = m;
    node* n = new node;
    n->data = rand() % 7;
  n->next= begin->next;
  begin->next = n;
    node* nn = new node;

    nn->data = rand() % 20;
    nn->next = begin->next;
    begin->next = nn;
    node* jj = new node;
    jj->data = 10;
    jj->next = begin->next;
    begin->next = jj;
   
  sort(begin);

  node* copy_m = begin;
  cout << "第一个链表:";
  while (copy_m->next) {

      cout << copy_m->next->data << ",";
      copy_m = copy_m->next;
  }
  node* begin2 = new node;
  begin2->next = NULL;
  node* m2 = new node;

  m2->data = rand() % 15;
  //cout << m->data;
  m2->next = begin2->next;
  begin2->next = m2;
  node* n2 = new node;
  n2->data = 5;
  n2->next = begin2->next;
  begin2->next = n2;
  node* nn2 = new node;

  nn2->data = 8;
  nn2->next = begin2->next;
  begin2->next = nn2;
  node* jj2 = new node;
  jj2->data = 10;
  jj2->next = begin2->next;
  begin2->next = jj2;
  node* copy_m2 = begin2;
  sort(begin2);
  cout << "第二个链表:";
  while (copy_m2->next) {

      cout << copy_m2->next->data << ",";
      copy_m2 = copy_m2->next;
  }
  cout << endl;
  cout << "交集:";
  node* c = new node;
  c->next = NULL;
  jiao(begin, begin2, c);
  while (c != NULL) {
      cout << c->next->data<<"->";
      c = c->next;
  }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值