Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- var problem = new Problem();
- problem.PrepareTestCase1();
- problem.Solve();
- problem = new Problem();
- problem.PrepareTestCase2();
- problem.Solve();
- problem = new Problem();
- problem.PrepareTestCase3();
- problem.Solve();
- Console.WriteLine("Press any key...");
- Console.ReadKey(true);
- }
- }
- public class ListNode
- {
- public int Value;
- public ListNode Next;
- public ListNode(int value)
- {
- Value = value;
- }
- }
- public class LinkedList
- {
- public int Length = 0;
- public ListNode Head = null, Tail = null;
- public void Add(int value)
- {
- if (Head == null)
- {
- Head = new ListNode(value);
- Tail = Head;
- }
- else
- {
- Tail.Next = new ListNode(value);
- Tail = Tail.Next;
- }
- Length++;
- }
- public void Add(LinkedList list)
- {
- if (Head == null)
- {
- Head = list.Head;
- Tail = Head;
- }
- else
- {
- Tail.Next = list.Head;
- Tail = list.Tail;
- }
- Length += list.Length;
- }
- }
- public class Problem
- {
- private LinkedList listA = new LinkedList(), listB = new LinkedList();
- private ListNode getIntersectionNode()
- {
- if (listA == null || listB == null)
- return null;
- if (listA.Tail != listB.Tail)
- return null; // both list must end with the same node if they intersect with each other
- var diff = Math.Abs(listA.Length - listB.Length);
- if (listA.Length > listB.Length)
- while (diff-- > 0)
- listA.Head = listA.Head.Next; // skip listA's head if listA has more elements than listB
- else
- while (diff-- > 0)
- listB.Head = listB.Head.Next; // skip listB's head if listB has more elements than listA
- while (listA.Head != listB.Head) // while not intersect
- {
- listA.Head = listA.Head.Next;
- listB.Head = listB.Head.Next;
- }
- return listA.Head;
- }
- public void Solve()
- {
- var intersectionNode = getIntersectionNode();
- Console.WriteLine("intersection = {0}", intersectionNode != null ? intersectionNode.Value.ToString() : "N/A");
- }
- public void PrepareTestCase1()
- {
- var intersection = new LinkedList();
- intersection.Add(8);
- intersection.Add(4);
- intersection.Add(5);
- listA.Add(4);
- listA.Add(1);
- listA.Add(intersection);
- listB.Add(5);
- listB.Add(0);
- listB.Add(1);
- listB.Add(intersection);
- }
- public void PrepareTestCase2()
- {
- var intersection = new LinkedList();
- intersection.Add(2);
- intersection.Add(4);
- listA.Add(0);
- listA.Add(9);
- listA.Add(1);
- listA.Add(intersection);
- listB.Add(3);
- listB.Add(intersection);
- }
- public void PrepareTestCase3()
- {
- listA.Add(2);
- listA.Add(6);
- listA.Add(4);
- listB.Add(1);
- listB.Add(5);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement