Here,we will learn how to create a linked list using c#.A linked list is a dataStructure which has nodes.The node has data and next pointer.Here the elements are not stored in contiguous locations,they are linked using pointers.
In the below program,we are creating a linked list by adding items to its end.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkedLists
{
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
public class Program
{
public static Node head;
public static Node dummy;
static void Main(string[] args)
{
Program.AddLast(1);
Program.AddLast(2);
Program.AddLast(3);
Program.AddLast(4);
Program.AddLast(5);
Program.AddLast(6);
}
public static void AddLast(int data)
{
Node toAdd = new Node(data);
toAdd.data = data;
toAdd.next = null;
if (head == null)
{
head = new Node(data);
//head2 = headd;
return;
}
else
{
Node last = head;
while (last.next != null)
last = last.next;
/* 6. Change the next of last node */
last.next = toAdd;
}
}
}
A linked list is represented by a pointer to the first node of linked list.The first node is called the head.If the list is empty,then value of head is NULL.
In the below program,we are creating a linked list by adding items to its end.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkedLists
{
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
public class Program
{
public static Node head;
public static Node dummy;
static void Main(string[] args)
{
Program.AddLast(1);
Program.AddLast(2);
Program.AddLast(3);
Program.AddLast(4);
Program.AddLast(5);
Program.AddLast(6);
}
public static void AddLast(int data)
{
Node toAdd = new Node(data);
toAdd.data = data;
toAdd.next = null;
if (head == null)
{
head = new Node(data);
//head2 = headd;
return;
}
else
{
Node last = head;
while (last.next != null)
last = last.next;
/* 6. Change the next of last node */
last.next = toAdd;
}
}
}
}
Comments
Post a Comment