Skip to content

Instantly share code, notes, and snippets.

@cypok cypok/list.cs
Created Feb 24, 2009

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Text;
namespace DoubleLinkedList
{
class ListNode
{
public ListNode next;
public ListNode prev;
public int value;
public ListNode(int value)
{
this.value = value;
this.prev = null;
this.next = null;
}
public ListNode(int value, ListNode prev, ListNode next)
{
this.value = value;
this.prev = prev;
this.next = next;
}
}
class List
{
private ListNode head;
private ListNode tail;
public List()
{
head = tail = null;
}
public List PushBack(int value)
{
if ( tail == null )
{
tail = head = new ListNode(value);
}
else
{
tail.next = new ListNode(value, tail, null);
tail = tail.next;
}
return this;
}
public List PushFront(int value)
{
if ( head == null )
{
tail = head = new ListNode(value);
}
else
{
head.prev = new ListNode(value, null, head);
head = head.prev;
}
return this;
}
public override string ToString()
{
if (head == null)
return "";
ListNode elem = head;
string result = elem.value.ToString();
while( (elem = elem.next) != null)
result += " " + elem.value.ToString();
return result;
}
}
class Program
{
static void Main(string[] args)
{
List list = new List();
list.PushBack(3);
list.PushFront(4);
list.PushBack(8);
list.PushBack(9);
Console.Write(list);
}
}
}
class ListNode
attr_accessor :prv, :nxt, :value
def initialize(value, options = {})
@value, @prv, @nxt = value, options[:prv], options[:nxt]
end
end
class List
def initialize
@head = @tail = nil
end
def push(place, value)
unless @head
@head = @tail = ListNode.new( value )
else
case place
when :front
@head.prv = ListNode.new value, :nxt => @head
@head = @head.prv
when :back
@tail.nxt = ListNode.new value, :prv => @tail
@tail = @tail.nxt
end
end
self
end
def to_s
return "" unless @head
elem = @head
result = "#{@head.value}"
result += " #{elem.value}" while elem = elem.nxt
result
end
end
list = List.new
list.push :back, 3
list.push :front, 4
list.push( :back, 8).push( :back, 9 )
puts list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.