数据结构&算法-双向链表
Posted 彩色墨水
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构&算法-双向链表相关的知识,希望对你有一定的参考价值。
双向链表
双向链表也是链表的一种,它每个数据结点中都有两个结点,分别指向其直接前驱和直接后继。所以我们从双向链表的任意一个结点开始都可以很方便的访问其前驱元素和后继元素。
代码
using System;
namespace DoubleLinkedList
{
class Program
{
static void Main(string[] args)
{
DoubleLink<string> doubleLink = new DoubleLink<string>("头");
doubleLink.AddNode(1, new Node<string>("第一名"));
doubleLink.AddNode(1, new Node<string>("第5名"));
doubleLink.AddNode(1, new Node<string>("第4名"));
doubleLink.AddNode(1, new Node<string>("第9名"));
doubleLink.AddNode(3, new Node<string>("第9名"));
doubleLink.RemoveNode(4);
doubleLink.AmendData(2, "被修改的");
doubleLink.TraversingList();
}
}
/// <summary>
/// 结点
/// </summary>
class Node<T>
{
public Node<T> next;
public Node<T> last;
T content;
public Node(T content)
{
this.content = content;
}
public void AmendData(T amend)
{
content = amend;
}
public T GetContent()
{
return content;
}
}
class DoubleLink<T>
{
Node<T> head; //头部不算个数,索引为0
public DoubleLink(T t)
{
head = new Node<T>(t);
}
int NodeNum = 0;
/// <summary>
/// 添加结点
/// </summary>
/// <param name="index"></param>
/// <param name="node"></param>
public void AddNode(int index, Node<T> node)
{
if (index < 1 || index > NodeNum + 1)
{
return;
}
Node<T> needNode = head;
if (index == NodeNum + 1)
{
for (int i = 0; i < NodeNum; i++)
{
needNode = needNode.next;
}
needNode.next = node;
node.last = needNode;
NodeNum++;
}
else
{
for (int i = 0; i < index; i++)
{
needNode = needNode.next;
}
needNode.last.next = node;
node.last = needNode.last;
node.next = needNode;
needNode.last = node;
NodeNum++;
}
}
/// <summary>
/// 删除结点
/// </summary>
/// <param name="index"></param>
public void RemoveNode(int index)
{
if (index < 1 || index > NodeNum)
{
return;
}
Node<T> needNode = head;
for (int i = 0; i < index; i++)
{
needNode = needNode.next;
}
needNode.last.next = needNode.next;
if (needNode.next != null)
{
needNode.next.last = needNode.last;
needNode.next = null;
}
needNode.last = null;
needNode = null;
}
/// <summary>
/// 查询结点
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public Node<T> GetNode(int index)
{
if (index < 1 || index > NodeNum)
{
return null;
}
Node<T> needNode = head;
for (int i = 0; i < index; i++)
{
needNode = needNode.next;
}
return needNode;
}
public Node<T> AmendData(int index, T content)
{
if (index < 1 || index > NodeNum)
{
return null;
}
Node<T> needNode = head;
for (int i = 0; i < index; i++)
{
needNode = needNode.next;
}
needNode.AmendData(content);
return needNode;
}
/// <summary>
/// 遍历链表
/// </summary>
public void TraversingList()
{
Node<T> curNode = head;
while (curNode != null)
{
Console.WriteLine(curNode.GetContent());
curNode = curNode.next;
}
}
}
}
以上是关于数据结构&算法-双向链表的主要内容,如果未能解决你的问题,请参考以下文章