Created
June 6, 2015 23:50
-
-
Save VegaFromLyra/52a629338d570d22db36 to your computer and use it in GitHub Desktop.
Insert items into double linked list in sorted order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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