Skip to content

Commit

Permalink
add solutions for Intersection-of-Two-Linked-Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
xcv58 committed Feb 19, 2015
1 parent a6244fe commit bed6a64
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Intersection-of-Two-Linked-Lists/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#include <stdio.h>

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *a = headA, *b = headB, *lastA = a, *lastB = b;
for (; a != NULL && b != NULL; lastA = a, lastB = b, a = a->next, b = b->next);
for (; b != NULL; lastB = b, b = b->next, headB = headB->next);
for (; a != NULL; lastA = a, a = a->next, headA = headA->next);
for (; headA != NULL && headB != NULL && headA != headB; headA = headA->next, headB = headB->next);
return (lastA != lastB) ? NULL :headA;
}
};

int main(int argc, char *argv[]) {
return 0;
}
20 changes: 20 additions & 0 deletions Intersection-of-Two-Linked-Lists/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Solution {

public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA, b = headB, lastA = a, lastB = b;
for (; a != null && b != null; lastA = a, lastB = b, a = a.next, b = b.next);
for (; b != null; lastB = b, b = b.next, headB = headB.next);
for (; a != null; lastA = a, a = a.next, headA = headA.next);
for (; headA != null && headB != null && headA != headB; headA = headA.next, headB = headB.next);
return (lastA != lastB) ? null :headA;
}
}
19 changes: 19 additions & 0 deletions Intersection-of-Two-Linked-Lists/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
s = set()
while headA is not None:
s.add(headA)
headA = headA.next
while headB is not None:
if headB in s:
return headB
headB = headB.next
return None

0 comments on commit bed6a64

Please sign in to comment.