Intersection function in Scala The problem is：


  Intersection: Given two (singly) linked lists, determine if the two
  lists intersect. Return the intersecting node. Note that the
  intersection is defined based on reference, not value. 
  
  That is, if the kth node of the first linked list is the exact same
  node (by reference) as the jth node of the second linked list, then
  they are intersecting. Below is an example:



The code I wrote is as following, may I know any improvement can be done?

  def intersecton[A](alist: List[A], blist:List[A]): Option[A]= (alist.last, blist.last)match{
    case (a,b) if (a!=b) =&gt; None
    case (_,_) if (alist.size&gt;1 &amp;&amp; blist.size&gt;1 &amp;&amp; alist(alist.size-2) != blist(blist.size-2)) =&gt; Some(alist.last)
    case (a,b) if (alist.size ==1||blist.size ==1)&amp;&amp; a==b =&gt; Some(a)
    case (_,_) =&gt; intersecton(alist.dropRight(1), blist.dropRight(1))
  }


Below is the test case I already run:

val list1: List[Int]=List(5,6, 1, 1, 4)
val list2: List[Int]=List(6, 1, 1,4)
&gt;&gt;6 

val list1: List[Int]=List(3,2,4)
val list2: List[Int]=List(5,6,7)
&gt;&gt;None


val list1: List[Int]=List(4,6,7)
 val list2: List[Int]=List(5,6,7)
&gt;&gt;6
intersecton(List(1, 2, 4), List(4, 5, 6)) incorrectly returns None.



You've asked several questions recently, and I keep seeing similar issues:


Using list.last: You have been advised to avoid traversing to the end of the list, for efficiency.  Lists should be manipulated at the head.
Functional thinking: These solutions involve too many tedious cases, and the code could be simplified by defining helper functions, or even restated entirely in terms of other functions.
Spelling: What's an "intersecton"?  (You previously misspelled "palindrome", twice.)
Inadequate testing: The counterexample cited above just happened to be the first test I tried, and it failed.  This isn't the first time I've seen an obviously wrong result.  Your first question was closed due to broken code, and it still hasn't been fixed.


You are welcome to use Code Review as a learning resource, but it would be a good idea to show some improvement between questions.