LeetCode160:Intersection of two Linked Lists
Posted on 2018-02-02 19:45 老刘想当个AI工程师 阅读(125) 评论(0) 收藏 举报法一 邦邦邦~~~~~~~
思想比较简单 运用了c++中的STL的set set这个东西详见此博客http://www.cnblogs.com/BeyondAnyTime/archive/2012/08/13/2636375.html
通过比较每个ListNode的地址,地址相同即开始相交,(注意:这里并不是比较每个单元的值 而是比较地址)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
std::set <ListNode*> node_set;//是ListNode *类型 存放的是每个ListNode的地址而不是具体的单元元素值
while(headA){
node_set.insert(headA);//向node_set中插入链表A的各个节点元素
headA=headA->next;
}
while(headB){
if(node_set.find(headB)!=node_set.end()){//如果B中有和A相同的元素 返回该元素
return headB;
}
headB=headB->next;
}
return NULL;
}
};
运用了set集合,set集合的时间复杂度是O(nlogn) 空间复杂度O(n)
思路二时间复杂度O(n) 空间复杂度O(1)
法二~~~邦邦邦
遍历A和B的链表长度(假设 A的长度是6 B的长度是8)
将headA向后移动lengthB-lengthA个位置(8-6=2)
这时再将headA和headB同时向后移动 一次移动一个 当相同即找到交点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int get_list_length(ListNode * head){
int len=0;
while(head){
len++;
head = head->next;
}
return len;
}
ListNode * forward_long_list(ListNode * head,int short_len ,int long_len){
int delta = long_len-short_len;
while(head && delta){
head = head->next;
delta--;
}
return head;
}
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int list_A_length = get_list_length(headA);
int list_B_length = get_list_length(headB);
if(list_A_length>list_B_length){
headA = forward_long_list(headA,list_B_length,list_A_length);
}
else{
headB = forward_long_list(headB,list_A_length,list_B_length);
}
while(headA && headB){
if(headA==headB){
return headA;
}
headA = headA->next;
headB = headB->next;
}
return null;
}
};
浙公网安备 33010602011771号