Zack Spidey Davidson Zack Spidey Davidson - 3 months ago 9
C# Question

Implementation of Queue using Linked List- It creates the Linked List but stops working after it prints

Here is what I have so far. I have generated a linked list but when the program prints the linked list out, a pop up comes up and it says my program has stopped working. I am using visual studio. I need to implement a queue using linked list. I am able to create it and print it out but when it prints out, the program stops. I have tried everything but I cannot seem to get this error to go away. This also happens when I try to use other methods in the linked list class but I did not include those methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CSCI3230_Project2_Zack_Davidson
{

class Program
{

static void Main(string[] args)
{

int count = 0;
LinkedList list = new LinkedList();
for (int i = 1; i <= 20; i++)
{
list.Add(new Node(i));
count++;
}
Console.WriteLine("I have generated a queue with 20 elements. I have printed the queue below.");
list.PrintNodes();

}
}

public class Node
{

public Node next;
public int data;
public Node(int val)
{
data = val;
next = null;
}
}

public class LinkedList
{
public TimeSpan runTimer;
public System.Diagnostics.Stopwatch
stopwatch = new System.Diagnostics.Stopwatch();

Node front;
Node current;

public void Add(Node n)
{
if (front == null)
{
front = n;
current = front;
}
else
{
current.next = n;
current = current.next;
}

}

public void PrintNodes()
{
Node print = front;
while (front != null)
{
Console.WriteLine(print.data);
print = print.next;
}

/*while (front != null)
{
Console.WriteLine(front.data);
front = front.next;
}*/
}
}//EndofNameSpace

Answer

Your program is running into an infinite loop here:

Node print = front;
while (front != null)
{
    Console.WriteLine(print.data);
    print = print.next;
}

front is never going to be null. You should have print!=null.