Bagus Arya Bagus Arya - 9 days ago 6
C# Question

How to print two Linked List program

Please help me, i trying to use two Linked list because i want the result is just like my 2 array element. Here is my code

class Program
{
int[] info = { 74, 90, 80, 63 };
int[] link = { 2, 6, 0, 3 };


static void Main(string[] args)
{
Program newProgram = new StrukturData.Program();

newProgram.Node();

Console.ReadLine();
}

public void Node()
{
LinkedList<int> infoList = new LinkedList<int>(info);
LinkedList<int> linkList = new LinkedList<int>(link);

foreach (var item in infoList)
{
Console.Write(item + " ");

foreach (var back in linkList)
{
Console.Write(back + " ");
}
}
}
}


Ouput

74 2 6 0 3 90 2 6 0 3 80 2 6 0 3 63 2 6 0 3


What i was expected

74 2 90 6 80 0 63 3


I think the problem is in my foreach statement. Im sorry my english is bad so i cann't talking to much:(, but i hope you guys can help me to get the result what i was expected :)

Answer

If you are looking for universal solution (which may be complex though), please, have a look at

Merge multiple lists with variable length "popping" elements from each

where my answer will do for any IEnumerable<T> (LinkedList<int>, int[] included) input:

 public void Node() {
   Console.Write(string.Join(" ", Merge(info, link)));
 }

Or if you insist on LinkedList<T>:

 public void Node() {
   LinkedList<int> infoList = new LinkedList<int>(info);
   LinkedList<int> linkList = new LinkedList<int>(link);

   Console.Write(string.Join(" ", Merge(infoList, linkList)));
 }

In case of you want to solve just your exact LinkedList<int> case:

 LinkedList<int> infoList = new LinkedList<int>(info);
 LinkedList<int> linkList = new LinkedList<int>(link); 

 // Enumerate each collection 
 using (var enInfo = infoList.GetEnumerator()) {
   using (var enLink = linkList.GetEnumerator()) {
     bool proceed = true;

     // until both exausted
     while (proceed) {
       proceed = false; 

       if (enInfo.MoveNext()) {
         proceed = true;

         Console.Write(enInfo.Current + "  ");
       }

       if (enLink.MoveNext()) {
         proceed = true;

         Console.Write(enLink.Current + "  ");
       } 
     }  
   }
 }
Comments