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;
    }
  • 相关阅读:
    电脑内存九大常见问题解决方案
    学会快速装系统 图解硬盘分区软件Norton Ghost使用
    XP和Win 7双系统安装说明和注意事项
    Linux gzip、gunzip
    kylin的状态栏(启动器)改成ubuntu之前的样子
    chrome安装HTTP测试扩展
    程序员重要的事情
    PD003-NET通用后台系统
    通用后台管理系统(ExtJS 4.2 + Spring MVC 3.2 + Hibernate)
    UNICODE与ANSI的区别
  • 原文地址:https://www.cnblogs.com/fenice/p/8712185.html
Copyright © 2011-2022 走看看