Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class Program
- {
- static void Main(string[] args)
- {
- var listA = new ListNode(new[] { 4, 5, 8, 4, 5 });
- var listB = new ListNode(new[] { 5, 0, 1, 8, 4, 5 });
- //var listA = new ListNode(new[] { 0, 9, 1, 2, 4 });
- //var listB = new ListNode(new[] { 3, 2, 4 });
- //var listA = new ListNode(new[] { 2, 6, 4 });
- //var listB = new ListNode(new[] { 1, 5 });
- var result = new Solution().GetIntersectionNode(listA, listB);
- Console.WriteLine(result != null ? result.val.ToString() : "no result");
- Console.WriteLine("Press any key...");
- Console.ReadKey(true);
- }
- }
- public class ListNode
- {
- public int val;
- public ListNode next;
- public ListNode(int x)
- {
- val = x;
- }
- public ListNode(int[] values)
- {
- int i = 0;
- ListNode current = null;
- while (i < values.Length)
- {
- if (i == 0)
- {
- current = this;
- current.val = values[i++];
- }
- else
- {
- current.next = new ListNode(values[i++]);
- current = current.next;
- }
- }
- }
- public int GetLength()
- {
- var length = 0;
- var current = this;
- while (current != null)
- {
- length++;
- current = current.next;
- }
- return length;
- }
- public int[] ToArray()
- {
- var list = new List<int>();
- var current = this;
- while (current != null)
- {
- list.Add(current.val);
- current = current.next;
- }
- return list.ToArray();
- }
- }
- public class Solution
- {
- public ListNode ListA, ListB;
- public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
- {
- var lengthA = headA.GetLength();
- var lengthB = headB.GetLength();
- int[] a, b;
- var currentA = headA;
- for (var i = 0; i < lengthA; i++)
- {
- if (i > 0) currentA = currentA.next;
- a = currentA.ToArray();
- var currentB = headB;
- for (var j = 0; j < lengthB; j++)
- {
- if (j > 0) currentB = currentB.next;
- b = currentB.ToArray();
- if (a.SequenceEqual(b))
- return currentB;
- }
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement