zoukankan      html  css  js  c++  java
  • 两个链表的第一个公共结点

    // test02.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    
    struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
    val(x), next(NULL) {
    }
    };
    
    class Solution {
    public:
    	ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2) {
    		int count1 = 0, count2 = 0,count=0;
    		ListNode *p1 = pHead1, *p2 = pHead2;
    		ListNode *p=NULL;
    		if (pHead1 == NULL || pHead2 == NULL) //如果两个链表有一个链表为空,返回空
    			return NULL;
    
    		while (p1!=NULL)//统计两个链表中的元素个数
    		{
    			count1++;
    			p1 = p1->next;
    		}
    		while (p2!=NULL)
    		{
    			count2++;
    			p2 = p2->next;
    		}
    
    		if (count1 > count2) //如果链表1的元素个数多余链表2中的元素个数
    		{
    			count = count1 - count2;
    			while (count--)
    			{
    				pHead1 = pHead1->next;
    			}
    			while (pHead1!=NULL&&pHead2!=NULL)//必须保证两个链表都不为空
    			{
    				if (pHead1->val == pHead2->val)
    				{
    					p = pHead1;
    					break;
    				}
    				else
    				{
    					pHead1 = pHead1->next;
    					pHead2 = pHead2->next;
    				}
    			}		
    		}
    			
    		else//如果链表2的元素个数多余链表1中的元素个数
    		{
    			count = count2 - count1;
    			while (count--)
    			{
    				pHead2 = pHead2->next;
    			}
    			while (pHead1 != NULL&&pHead2 != NULL)
    			{
    				if (pHead1->val == pHead2->val)
    				{
    					p = pHead1;
    					break;
    				}
    				else
    				{
    					pHead1 = pHead1->next;
    					pHead2 = pHead2->next;
    				}
    			}
    
    			
    
    		}
    		return p;
    	}
    };
    
    int main()
    {
    	ListNode a(1);
    	ListNode b(2);
    	ListNode c(3);
    	ListNode d(4);
    	ListNode e(5);
    	ListNode f(6);
    	ListNode g(7);
    	ListNode h(8);
    	a.next = &b;
    	b.next = &c;
    	c.next = &f;
    	f.next = &g;
    	g.next = &h;
    	d.next = &e;
    	e.next = &f;
    
    	Solution so;
    	ListNode *p1 = &a;
    	ListNode *p2 = &d;
    
    ListNode *ln=so.FindFirstCommonNode(p1,p2);
    
    
    	//while (p1!=NULL)
    	//{
    	//	cout << p1->val << "  ";
    	//	 p1 = p1->next;
    	//}
    	//cout << endl;
    	//while (p2 != NULL)
    	//{
    	//	cout << p2->val << "  ";
    	//	p2 = p2->next;
    	//}
    
    	cout << "第一个公共的节点是:" <<ln->val << endl;
    
    return 0;
    }
    
    分析:先算出长的序列比短的序列多n个,然后长的序列先走n步,然后长序列和短序列一起走,直到两个序列的值相等即可
  • 相关阅读:
    django-缓存的应用
    Faster-RCNN用于场景文字检测训练测试过程记录(转)
    faster-rcnn在ubuntu16.04环境下的超级详细的配置(转)
    Effective C++读书笔记(转)
    c++中的static,const,const static以及它们的初始化
    [leetcode]Validate Binary Search Tree 验证二叉搜索树
    二叉树的遍历方式(迭代)
    c++中string与int之间的相互转换
    c++中 cin,cin.get(),cin.getline(),getline()用法说明
    N皇后问题代码
  • 原文地址:https://www.cnblogs.com/wdan2016/p/5962189.html
Copyright © 2011-2022 走看看