Wednesday, April 18, 2007

3. Doubly-linked list

In addition to the properties of the singly-linked list, each node in a doubly-linked list contains a link to the previous node in the chain.
Program.cs


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

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

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

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

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

TempNode = head;
while (TempNode.Next != null)
{

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

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

do
{
Console.WriteLine(currNode.Data);
currNode = currNode.Prev;
} while (currNode != head);

Console.Read();
}
}
}


Node.cs

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

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

No comments: