Created
August 31, 2013 03:36
-
-
Save czxttkl/6396076 to your computer and use it in GitHub Desktop.
Two linked lists (simple link, not double link) heads are given: headA, and headB;
it is also given that the two lists intersect, thus after the intersection they have the
same elements to the end. Find the first common element (without modifying the lists
elements or using additional datastructures)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.czxttkl.homework; | |
import java.util.LinkedList; | |
public class HomeWork1b { | |
private static <T> void findFirstElement(LinkedList<T> linkA, | |
LinkedList<T> linkB) { | |
int offsetA = 0; | |
int offsetB = 0; | |
if (linkB.size() > linkA.size()) | |
offsetB = linkB.size() - linkA.size(); | |
else | |
offsetA = linkA.size() - linkB.size(); | |
int i = offsetA; | |
while (offsetA < linkA.size()) { | |
if (!linkA.get(offsetA).equals(linkB.get(offsetB))) | |
i = offsetA + 1; | |
offsetA++; | |
offsetB++; | |
} | |
System.out.println("The first overlapped element is :"); | |
System.out.println((i + 1) + "th of LinkedListA"); | |
System.out.println( (i + 1 + offsetB - offsetA) + "th of LinkedListB"); | |
} | |
public static void main(String... args) { | |
LinkedList<Integer> linkA = new LinkedList<Integer>(); | |
LinkedList<Integer> linkB = new LinkedList<Integer>(); | |
linkA.add(1); | |
linkA.add(1); | |
linkA.add(1); | |
linkA.add(2); | |
linkA.add(3); | |
linkA.add(4); | |
linkA.add(5); | |
linkB.add(5); | |
linkB.add(2); | |
linkB.add(3); | |
linkB.add(4); | |
linkB.add(5); | |
findFirstElement(linkA, linkB); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment