【剑指offer系列】 两个链表的第一个公共节点___37
来源:互联网 发布:霍尔果斯万游网络 编辑:程序博客网 时间:2024/05/17 04:34
题目描述:
输入两个单链表,找出他们的第一个公共节点。若没有,则返回NULL
分析:
如果两个单链表有公共节点,那么在交点后的每一个节点都是公共的。因此两个单链表的构型必然是下图所示的Y型。
1)利用栈的先进后出,将两个链表的所有节点都入栈。然后再依次出栈。找出最后一个相同节点,即为第一个公共节点.但是这种方法需要两个栈作为辅助空间
2)首先我们可以分别遍历两个链表,得到其长度len1和len2。然后使用快慢指针,使较长链表的指针先走len1-len2步,然后两个指针同时每次走一步。当两个指针相遇时,即为第一个公共节点
代码:
int getListLength(listNode *head){ listNode *p=head; int len=0; while(p){ ++len; p=p->next; } return len;}listNode *firstCommon(listNode *head1,listNode *head2){ int len1=getListLength(head1); int len2=getListLength(head2); if(len1==0||len2==0) return NULL; listNode *p=head1,*q=head2; while(len1>len2){ p=p->next; --len1; } while(len1<len2){ q=q->next; --len2; } while(p&&q&&p!=q){ p=p->next; q=q->next; } return p;}
0 0
- 【剑指offer系列】 两个链表的第一个公共节点___37
- 剑指offer-两个链表的第一个公共节点
- 【剑指offer】两个链表的第一个公共节点
- 剑指offer-两个链表的第一个公共节点
- 【剑指offer】两个链表的第一个公共节点
- 剑指offer------两个链表的第一个公共节点
- 《剑指offer》两个链表的第一个公共节点
- 剑指offer-两个链表的第一个公共节点
- 剑指offer--两个链表的第一个公共节点
- 剑指offer 两个链表的第一个公共节点
- 剑指offer系列之三十五:两个链表的第一个公共节点
- 剑指offer系列之35:两个链表的第一个公共节点
- 【刷题剑指offer】两个链表的第一个公共节点
- 剑指offer面试题37 两个链表的第一个公共节点
- [剑指offer][面试题37]两个链表的第一个公共节点
- 剑指offer 面试题37—两个链表的第一个公共节点
- 剑指offer之两个链表的第一个公共节点
- 剑指offer 37 - 两个链表的第一个公共节点
- 文章标题
- JSP页面隔行换色
- 在唯一密钥属性“value”设置为“default.aspx”(或者index.asp等)时,无法添加类型为“add”的重复集合项
- 直接选择排序
- excel导入
- 【剑指offer系列】 两个链表的第一个公共节点___37
- (Kevin笔记四)activity相互切换的时候怎么传递和刷新数据
- 归并排序
- 怎样设置Windows 7远程桌面连接
- 忽略IE浏览器弹出的“允许阻止的内容”
- tomcat(5)servlet容器
- PHP学习路线
- Linux目录结构
- OVAL学习笔记