Advertisement
Evyatar12

separate lists

Jan 8th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Stacks
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.         }
  14.  
  15.         static Stack<Node<T>> pushListToStack<T>(Node<T> list, ref int counter)
  16.         {
  17.             Stack<Node<T>> stack = new Stack<Node<T>>();
  18.  
  19.             counter = 0;
  20.  
  21.             while (list != null)
  22.             {
  23.                 stack.push(list);
  24.                 list = list.getNext();
  25.                 counter++;
  26.             }
  27.  
  28.             return stack;
  29.         }
  30.  
  31.         static void separateLists<T>(ref Node<T> list1, ref Node<T> list2) {
  32.             int length1 = 0,
  33.                 length2 = 0;
  34.  
  35.             Stack<Node<T>> s1 = pushListToStack<T>(list1, ref length1),
  36.                            s2 = pushListToStack<T>(list2, ref length2);
  37.            
  38.             list1 = null;
  39.             list2 = null;
  40.  
  41.             // while we're still in the shared part
  42.             while (!s1.isEmpty() && !s2.isEmpty()
  43.                     && s1.top().Equals(s2.top())) {
  44.                 // if the first list is longer than the second
  45.                 if (length1 >= length2) {
  46.                     list1 = s1.pop();
  47.                 }
  48.                    
  49.                 else {
  50.                     list2 = s2.pop();
  51.                 }
  52.             }
  53.  
  54.             if (!s1.isEmpty()) {
  55.                 if (length1 < length2) {
  56.                     list1 = s1.pop();
  57.                     list1.setNext(null);
  58.                 }
  59.  
  60.                 // get all the left nodes in the stack of list1
  61.                 while (!s1.isEmpty())
  62.                     list1 = s1.pop();
  63.             }
  64.  
  65.  
  66.             if (!s2.isEmpty()) {
  67.                 if (length1 >= length2) {
  68.                     list2 = s2.pop();
  69.                     list2.setNext(null);
  70.                 }
  71.  
  72.                 // get all the left nodes in the stack of list1
  73.                 while (!s2.isEmpty())
  74.                     list2 = s2.pop();
  75.             }
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement