views:

70

answers:

3

How to represent a two way(doubly) linked list?

+4  A: 

It's a linked list where each node has references to the next and previous nodes.

http://en.wikipedia.org/wiki/Doubly-linked_list

quantumSoup
+1  A: 

Pseudocode:

list-node
{
  some-data
  pointer-or-reference to prev-list-node
  pointer-or-reference to next-list-node
}

That way, you can have:

current-node = beginning
current-node = current-node -> next-list-node
current-node = current-node -> prev-list-node

To "move" forwards and backwards. Syntax depends on language.

eruciform
A: 

In C#:

internal class ListNode<T> {

    public T Item { get; set; }
    public ListNode Prev { get; set; }
    public ListNode Next { get; set; }

}

public class List<T> {

    public List() { Head = Tail = null; }

    public void Add(T item) {
        var node = new ListNode<T>(item);
        if(IsEmpty)
           Head = Tail = node;
        else {
           node.Prev = Tail;
           Tail.Next = node;
           Tail = node;
        }        
    }

    protected ListNode<T> Head { get; set; }
    protected ListNode<T> Tail { get; set; }

    public bool IsEmpty { get { return Head == null; } }

}

et cetera...

Mau