Wednesday, April 18, 2007

2. Singly-linked list




Each node consists of one data member and one link to the next node. The last node in the chain will always point to a null value.

My implementation consists of two cs files including two classes.

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace myLinkedList
{
class Program
{
static void Main(string[] args)
{
char Answer='y';
Node n;
Node head=new Node();
Node currNode;
currNode = head;

while (Answer == 'y')
{
n = new Node();
Console.WriteLine("Enter Node Data:");
n.Data = int.Parse(Console.ReadLine());
currNode.Next = n;
currNode = n;

Console.WriteLine("Answer (y/n): ");
Answer=char.Parse(Console.ReadLine());
}

Console.WriteLine("Printing the Node Data:");

while (head.Next != null)
{

head = head.Next;
Console.WriteLine(head.Data);
}

Console.Read();


}
}
}


myNode.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace myLinkedList
{
public class Node
{
public Node()
{
Data = 0;
Next = null;
}
public int Data;
public Node Next;

}
}

OVERVIEW:
Although, this program produces the output I desire, it causes a memory leak, doesn't it?

Notice the line: head = head.Next;

There is a virtual head node that is hidden. If we intended to create 3 nodes, the program actually creates 4 nodes. Then it starts printing the data by skipping the first node.

5 comments:

Anonymous said...

I just love your weblog! Very nice post! Still you can do many things to improve it.

Anonymous said...

Thanks for sharing this link, but unfortunately it seems to be down... Does anybody have a mirror or another source? Please answer to my post if you do!

I would appreciate if a staff member here at csharpeasy.blogspot.com could post it.

Thanks,
William

Anonymous said...

Greetings,

I have a question for the webmaster/admin here at csharpeasy.blogspot.com.

May I use some of the information from your post above if I provide a link back to your site?

Thanks,
Harry

Anonymous said...

Hi,

Thanks for sharing the link - but unfortunately it seems to be not working? Does anybody here at csharpeasy.blogspot.com have a mirror or another source?


Thanks,
Jack

Anonymous said...

Greetings,

This is a question for the webmaster/admin here at csharpeasy.blogspot.com.

May I use part of the information from your post above if I provide a backlink back to your site?

Thanks,
William