zoukankan      html  css  js  c++  java
  • 打印两个有序链表的公共部分(C++实现)

    代码:

    #include <iostream>
    typedef class Node{
    public:
      int value;
      Node* Next;
      Node(int data):Next(NULL){
        this->value = data;
      }
    }Node,*node;
    void printCommonpart(node &head1,node &head2){
      std::cout << "链表的公共部分:" << ' ';
      while(head1 != NULL&&head2!=NULL){
          if(head1->value < head2->value){
            head1=head1->Next;
          }
          else if(head1->value > head2->value){
            head2=head2->Next;
          }
          else{
            std::cout << head1->value << ' ';
            head1=head1->Next;
            head2=head2->Next;
          }
      }
    }
    int main()
    {
      Node *n1 = new Node(1);
      Node *n2 = new Node(2);
      Node *n3 = new Node(3);
      Node *n4 = new Node(4);
      Node *n5 = new Node(5);
      Node *pHead1 = n1;
      n1->Next = n2;
      n2->Next = n3;
      n3->Next = n4;
      n4->Next = n5;
      Node *n2_1 = new Node(1);
      Node *n2_2= new Node(3);
      Node *n2_3= new Node(5);
      Node *n2_4= new Node(7);
      Node *n2_5= new Node(9);
      Node *pHead2 = n2_1;
      n2_1->Next = n2_2;
      n2_2->Next = n2_3;
      n2_3->Next = n2_4;
      n2_4->Next = n2_5;
      printCommonpart(pHead1,pHead2);
     
      return 0;
    }
     
    测试结果:
     
     
  • 相关阅读:
    AVL平衡二叉树
    算法集锦(二)
    算法集锦(一)
    选择问题 and 字谜游戏问题
    TF-IDF与余弦相似性的应用
    一致性哈希算法
    Cache缓存
    布隆过滤器
    信号
    设置用户ID和设置组ID
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13424212.html
Copyright © 2011-2022 走看看