首页 > 学院 > 开发设计 > 正文

链表的第一个公共节点

2019-11-08 01:22:22
字体:
来源:转载
供稿:网友
应该假设每个节点 是用指针直针来连接, 不然必须要用递归或者遍历完才能说明是公共的。 公共的意思是在内存上占用的空间相同/*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { }};*/class Solution {public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { ListNode *p1 = pHead1, *p2 = pHead2; int len1 = lenofList(pHead1); int len2 = lenofList(pHead2); if(len1 == 0 || len2 == 0) return nullptr; while(len1 > len2){ p1 = p1 -> next; --len1; } while(len2 > len1){ p2 = p2 -> next; --len2; } while(p1 != p2 && p1 != nullptr && p2 != nullptr){ p1 = p1 ->next ; p2 = p2 ->next ; } return p1; } template <typename T> inline int lenofList(T *pHead){ T *p = pHead; int len = 0; while(p != nullptr){ p = p -> next; ++len; } return len; }};
上一篇:WCF--MSMQ

下一篇:函数和二维数组

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表