添加Lesson10
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
namespace Lesson10_LinkedList
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
#region 知识点一 LinkedList
|
||||
//LinkedList<T> 是一个双向链表
|
||||
//是C#为我们封装好的一个数据结构
|
||||
#endregion
|
||||
|
||||
#region 知识点二 声明
|
||||
//需要引用命名空间 System.Collections.Generic
|
||||
|
||||
//链表对象,需要掌握两个类
|
||||
//一个是链表本身 LinkedList<T>,一个是链表节点 LinkedListNode<T>
|
||||
|
||||
LinkedList<int> linkedList = new LinkedList<int>();
|
||||
LinkedList<string> linkedList2 = new LinkedList<string>();
|
||||
#endregion
|
||||
|
||||
#region 知识点三 增删查改
|
||||
|
||||
|
||||
//增
|
||||
//1.在链表尾部添加元素
|
||||
linkedList.AddLast(1);
|
||||
//2.在链表头部添加元素
|
||||
linkedList.AddFirst(2);
|
||||
//3.在某一个节点之后添加一个节点
|
||||
// 要指定节点,先得到上一个节点
|
||||
LinkedListNode<int> n = linkedList.Find(1);
|
||||
linkedList.AddAfter(n, 3);
|
||||
//4.在某一个节点之前添加一个节点
|
||||
// 要指定节点,先得到下一个节点
|
||||
linkedList.AddBefore(n, 4);
|
||||
|
||||
|
||||
//删
|
||||
//1.移除头节点
|
||||
linkedList.RemoveFirst();
|
||||
//2.移除尾节点
|
||||
linkedList.RemoveLast();
|
||||
//3.移除指定节点
|
||||
// 要指定节点,先找到节点
|
||||
linkedList.Remove(4);//根据值移除节点
|
||||
//4.清空
|
||||
linkedList.Clear();
|
||||
|
||||
linkedList.AddFirst(1);
|
||||
linkedList.AddLast(2);
|
||||
|
||||
//查
|
||||
//1.头节点
|
||||
LinkedListNode<int> first = linkedList.First;
|
||||
//2.尾节点
|
||||
LinkedListNode<int> last = linkedList.Last;
|
||||
//3.查找指定节点
|
||||
// 无法通过下标获取指定元素
|
||||
// 只能遍历查找节点
|
||||
LinkedListNode<int> node = linkedList.Find(1);//根据值查找节点
|
||||
Console.WriteLine(node.Value);
|
||||
node = linkedList.FindLast(1);//找不到会返回空
|
||||
//4.判断是否包含某个值
|
||||
bool contains = linkedList.Contains(1);
|
||||
|
||||
|
||||
//改
|
||||
//先得到节点,再修改节点的值
|
||||
Console.WriteLine(linkedList.First.Value);
|
||||
linkedList.First.Value = 100;
|
||||
Console.WriteLine(linkedList.First.Value);
|
||||
#endregion
|
||||
|
||||
#region 知识点四 遍历
|
||||
//1.使用foreach遍历
|
||||
foreach (var item in linkedList)
|
||||
{
|
||||
Console.WriteLine(item);
|
||||
}
|
||||
//2.通过节点遍历
|
||||
//从头节点开始遍历
|
||||
LinkedListNode<int> temp = linkedList.First;
|
||||
while (temp != null)
|
||||
{
|
||||
Console.Write(temp.Value + " ");
|
||||
temp = temp.Next;//指向下一个节点
|
||||
}
|
||||
//从尾节点开始遍历
|
||||
temp = linkedList.Last;
|
||||
while (temp != null)
|
||||
{
|
||||
Console.WriteLine(temp.Value + " ");
|
||||
temp = temp.Previous;//指向上一个节点
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user