📄 program.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericSamp
{
public class Student //定义学生类
{
private string StudentName; //学生姓名
private int StudentAge; //年龄
public Student(string name, int age) //构造函数
{
this.StudentName = name;
this.StudentAge = age;
}
//重载ToString方法,实现学生类的输出
public override string ToString()
{
return this.StudentName + ":年龄" + this.StudentAge + "岁";
}
}
public class Node<T>
{
T data; //T类型的数据域
Node<T> next; //指向域
public Node(T data) //构造方法
{
this.data = data;
this.next = null;
}
public T Data //定义Data属性
{
get { return this.data; }
set { data = value; }
}
public Node<T> Next //定义节点属性
{
get { return this.next; }
set { this.next = value; }
}
//实现添加节点
public void Append(Node<T> newNode) //
{
if (this.next == null)
{
this.next = newNode;
}
else
{
next.Append(newNode);
}
}
//重载ToString方法,输出节点
public override string ToString()
{
string output = data.ToString();
if (next != null)
{
output += ", " + next.ToString();
}
return output;
}
}
public class LinkedList<T>
{
Node<T> headNode = null; //头节点
public void Add(T data) //将数据添加到链表中
{
if (headNode == null)
{
headNode = new Node<T>(data);
}
else
{
headNode.Append(new Node<T>(data));
}
}
//为线性链表创建一个索引器。
public T this[int index]
{
get
{
int temp = 0;
Node<T> node = headNode;
while (node != null && temp <= index)
{
if (temp == index)
{
return node.Data;
}
else
{
node = node.Next;
}
temp++;
}
return default(T);
}
}
//本类的ToString方法被重写,用以调用headNode的ToString()方法。
public override string ToString()
{
if (this.headNode != null)
{
return this.headNode.ToString();
}
else
{
return string.Empty;
}
}
}
class Program
{
static void Main(string[] args)
{
//实例化一个int类型的LinkedList对象
LinkedList<int> intList = new LinkedList<int>();
for (int i = 0; i < 5; i++) //向其中添加五个节点
{
intList.Add(i);
}
Console.WriteLine("整型List的内容为:");
Console.WriteLine(intList);
//实例化一个Student类型的LinkedList对象
LinkedList<Student> StudentList = new LinkedList<Student>();
//添加节点
StudentList.Add(new Student("张三", 20));
StudentList.Add(new Student("李四", 21));
StudentList.Add(new Student("王五", 23));
StudentList.Add(new Student("赵六", 19));
Console.WriteLine("Student类型List的内容为:");
Console.WriteLine(StudentList);
//获取特定位置节点
Console.WriteLine("第二个整数为:" + intList[1]);
Student s = StudentList[1];
Console.WriteLine("第二个学生为" + s);
Console.ReadLine();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -