《Thinking In Algorithm》04.单向链表和双向链表的区别

A node in a singly linked list has only a Next reference. Each node is referenced by a preceeding node (including the first node, which will be referenced by the list Head or from the last node in the case of a circularly linked list). In order to remove a node, the preceeding node must be made to reference the removed node's following node.

However, you cannot find the preceeding node directly; you have to search the list until you find it.

For example, suppose you want to remove node4 from this list, given only a reference to node4:

head->node1.next->node2.next->node3.next->node4.next->node5.next->null

You need to update the 'next' reference of node3 to reference node5:

head->node1.next->node2.next->node3.next->node5.next->null

In order to find node3 to update it's 'next' reference, you would need to start at 'head' and work your way through the list until you reach node4, remembering the previous node at each iteration. That is an O(N) operation.

Conversely, with a doubly linked list:

head->node1.next->node2.next->node3.next->node4.next->node5.next->null
       <-.prev         <-.prev           <-.prev          <-.prev          <-.prev

If you want to delete a node, you just need to do this:

class Node
{
      Node Next;
      Node Prev;
}

DeleteNode(Node node)
{
     node.Prev.Next = node.Next;
}

Which is an O(1) operation.


Summary:

A doubly-linked listmakes it very easy (code wise) to delete or insert entries. If you have a pointer to a node, any node, and you want to either delete that one or else insert another before or after it, then having access to both "next" and "prev" node pointers makes this very, very easy code. And fast, too. 

A singly-linked list only has links going in one direction (forward or backward can't really be told apart in this case) and if you want to just delete a node where you have only the pointer to it, you are kind of in trouble. You need to start at the beginning of the linked list, search through it to find the node that points to the node you are supposed to delete, and then you can do it. As you can imagine, this is more time consuming and it is more code, as well. But it's very easy to insert a node at the head of a singly-linked list





References:



http://answers.yahoo.com/question/index?qid=20130729013025AAzeInE


http://social.msdn.microsoft.com/Forums/vstudio/en-US/270bebdb-9032-4fc1-97c6-bc017d7e0a45/when-to-use-single-linked-list-and-when-to-use-double-linked-list?forum=csharpgeneral


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值