zoukankan      html  css  js  c++  java
  • 判断链表有公共点

    判断两个链表是否相汇,可以通过将第一个链表的尾部与第二个链表的头部相连接,如果链表形成了环,则说明链表相汇了。

    /*
    * 两个链表是否公共结点
    */
    #include<iostream>
    #include<ctime>
    #include<cstdlib>
    #include<cstdio>
    using namespace std;
    typedef struct node* link;
    typedef struct node{
        int value;
        link next;
        node(){
            value=-1;
            next=NULL;
        }
        node(int v){
            value=v;
            next=NULL;
        }
    }Node;
    
    void GenerateList(link& head1,link& head2){
        int n=rand()%100+1;
        head1=new Node();
        head2=new Node();
        link p1=head1,p2=head2;
        for(int i=0;i<n;i++){
            int x=rand()%100+1;
            p1->next=new Node(x);
            p1=p1->next;
        }
        int m=rand()%100+1;
        for(int i=0;i<m;i++){
            int x=rand()%100+1;
            p2->next=new Node(x);
            p2=p2->next;
        }
        p1->next=p2;  //if this statement is deleted, the two lists will have no common points;
        printf("the random common point's address:%d
    ",p2);
        int k=rand()%100+1;
        for(int i=0;i<k;i++){
            int x=rand()%100+1;
            p2->next=new Node(x);
            p2=p2->next;
        }
        head1->value=n+k+1;
        head2->value=m+k;
    }
    
    bool FindCircle(link head){
        link p=head;
        while(p->next!=NULL){
            p=p->next;
            if(p==head){
                return true;
            }
        }
        return false;
    }
    
    int main(){
        srand((unsigned)time(NULL));
        link head1=NULL,head2=NULL;
        GenerateList(head1,head2);
    
        // connect tail of list1 to the head of list2
        link p=head1;
        while(p->next!=NULL) p=p->next;
        p->next=head2;
    
        //judge whether there exists a circle
        if(FindCircle(head2)){
            if(head1->value<head2->value){
                int count=head2->value-head1->value;
                while(count--){
                    head2=head2->next;
                }
            }else{
                int count=head1->value-head2->value;
                while(count--){
                    head1=head1->next;
                }
            }
            while(head1!=head2){
                head1=head1->next;
                head2=head2->next;
            }
            printf("the common point's address:%d
    ",head1);
        }else{
            printf("No common nodes
    ");
        }
        return 0;
    }
  • 相关阅读:
    NSURLSession学习笔记(二)Session Task
    NSURLSession学习笔记(一)简介
    iOS Core Animation 简明系列教程
    iOS夯实:RunLoop
    mysql主从复制读写分离
    git文件名大小写问题
    mysql zip 安装
    maven dependencies与dependencyManagement的区别
    Eclipse使用技巧
    相关开发软件http代理设置 windows
  • 原文地址:https://www.cnblogs.com/fenice/p/8712185.html
Copyright © 2011-2022 走看看