[C语言][LeetCode][160]Intersection of Two Linked Lists
2016-04-14 21:39
507 查看
题目
Intersection of Two Linked ListsWrite a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
标签
Linked List难度
简单分析
题目意思是判断两个链表是否有交集,如果有,返回交集开始的地方。做法是先比较链表A和链表B,哪个比较长,接着长的链表先步进,走到跟短的链表起始位置一样了,然后逐个判断是否有相交的地方。C代码实现
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { struct ListNode *LA, *LB; struct ListNode *h1, *h2; int lenA=0, lenB=0, step=0; if(!headA || !headB) return NULL; LA = headA; LB = headB; while(LA) { lenA++; LA = LA->next; } while(LB) { lenB++; LB = LB->next; } if(lenA >= lenB) { step = lenA - lenB; h1 = headA; h2 = headB; } else { step = lenB - lenA; h1 = headB; h2 = headA; } while(h1 && step) { step--; h1 = h1->next; } while(h1 && h2) { if(h1->val == h2->val) return h1; h1 = h1->next; h2 = h2->next; } return NULL; }
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- Lua和C语言的交互详解
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C语言自动生成enum值和名字映射代码
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构
- C语言实现选择排序、冒泡排序和快速排序的代码示例
- 探讨C语言的那些小秘密之断言
- C语言实现BMP转换JPG的方法
- 深入探讨C语言中局部变量与全局变量在内存中的存放位置