Implementing a queue using a linked list. It creates a Linked List but stops working after printing it.

Here's what I have so far. I created a linked list, but when the program prints the linked list, a popup appears saying that my program has stopped working. I am using visual studio. I need to implement a queue using a linked list. I can create it and print it, but when it prints, the program stops. I've tried everything, but I can't 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 haven't used 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

      

+3


source to share


1 answer


Your program runs in an infinite loop:

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

      



the front will never be empty. You must have print! = Null.

+4


source







All Articles