Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created June 6, 2015 23:50
Show Gist options
  • Save VegaFromLyra/52a629338d570d22db36 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/52a629338d570d22db36 to your computer and use it in GitHub Desktop.
Insert items into double linked list in sorted order
using System;
namespace SortedDoubleLinkedList
{
public class Program
{
public static void Main(string[] args)
{
var sortedList = new SortedDoubleLinkedList();
sortedList.Add(5);
sortedList.Add(3);
sortedList.Add(9);
sortedList.Add(7);
sortedList.Add(4);
Console.WriteLine("Entries in the list are");
sortedList.Display();
}
}
class Node {
public Node(int data) {
Data = data;
}
public int Data {get; private set;}
public Node Prev {get; set;}
public Node Next {get; set;}
}
class SortedDoubleLinkedList {
Node head;
Node tail;
public void Add(int data) {
if (head == null) {
head = new Node(data);
tail = head;
} else if (data <= head.Data) {
addAtHead(data);
} else if (data >= tail.Data) {
addAtTail(data);
} else {
Node current = head;
while (current.Next != null) {
if ((current.Data < data) && (data <= (current.Next).Data)) {
Node newNode = new Node(data);
Node next = current.Next;
current.Next = newNode;
newNode.Prev = current;
newNode.Next = next;
next.Prev = newNode;
break;
}
current = current.Next;
}
}
}
public void Display() {
Node current = head;
while (current != null) {
Console.Write(current.Data + " ");
current = current.Next;
}
Console.WriteLine();
}
void addAtHead(int data) {
Node newNode = new Node(data);
newNode.Next = head;
head.Prev = newNode;
head = newNode;
}
void addAtTail(int data) {
Node newNode = new Node(data);
tail.Next = newNode;
newNode.Prev = tail;
tail = newNode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment