# 数据结构（2）链表的应用

链表表示的一列元素，由一系列的节点（Node）构成，是一种递归数据结构。节点是一个能够包含任何类型数据的抽象实体，它所包含的指向节点的应用体现了他在链表中的作用。

``` private class Node
{
public T Data;
public Node Next;
public Node(T data)
{
Data = data;
}
}```

1.实现一种泛型栈数据结构

```class NodeStack<T>:IEnumerable
{
private int N;
private Node first;

public T firstData()
{
return first.Data;
}
public int Size()
{
return N;
}
public void Push(T item)
{
N++;
var oldFirst = first;
first = new Node(item);
first.Next = oldFirst;
}
public T Pop()
{
--N;
var oldFirst = first;
first = first.Next;
return oldFirst.Data;
}
private class Node
{
public T Data;
public Node Next;
public Node(T data)
{
Data = data;
}
}

public IEnumerator GetEnumerator()
{
var oldFirst = first;
while (first!=null)
{
var node = first;
first = first.Next;
yield return node.Data;
}
first = oldFirst;
}
}```

2.实现一种泛型队列

``` class NodeQueue<T>:IEnumerable
{
private int N;
private Node first;
private Node last;
public bool isEmpty()
{
return first == null;
}
public int Size()
{
return N;
}
public void enqueue(T item)
{
var oldLast = last;
last = new Node(item);
if (isEmpty()) first = last;
else
oldLast.Next = last;
N++;
}
public T dequeue()
{
N--;
var oldFirst = first;
first = first.Next;
if (isEmpty()) last = null;
return oldFirst.Data;

}
private class Node
{
public T Data;
public Node Next;
public Node(T data)
{
Data = data;
}
}

public IEnumerator GetEnumerator()
{
var oldFirst = first;
while (first != null)
{
var node = first;
first = first.Next;
yield return node.Data;
}
first = oldFirst;
}
}```

原文作者：msp的昌伟哥哥
原文地址: https://www.cnblogs.com/mantgh/p/3975841.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。