本帖最后由 剑弑 于 2018-9-14 22:02 编辑
今天面试的时候既然有一个让我写个单链表类,当时就懵了。单链表我也只是记得太概的思路而已,要写也不可能在哪短短的时间里的出来吧。哎,又要惨了,吓得我面试完回来马上看看单链表类的实现,防止下次又不记得。
理论的知识我也不多说了,就直接看代码吧!!!
[C#] 纯文本查看 复制代码 public class Node<T>
{
public T Data { get; set; }
public Node<T> Next { get; set; }
public Node(T item)
{
this.Data = item;
this.Next = null;
}
public Node()
{
this.Data = default(T);
this.Next = null;
}
}[/mw_shl_code
[mw_shl_code=csharp,true]public class LinkList<T>
{
public Node<T> Head { get; set; }
public LinkList()
{
Head = null;
}
/// <summary>
/// 增加新元素到链尾
/// </summary>
/// <param name="item"></param>
public void Append(T item)
{
Node<T> foot = new Node<T>();
Node<T> A = new Node<T>();
if (Head==null)
{
Head = foot;
return;
}
A = Head;
while (A.Next!=null)
{
A = A.Next;
}
A.Next = foot;
}
/// <summary>
/// 删除链表元素
/// </summary>
public void Delete(int i)
{
if (i==1)//表头
{
Head = Head.Next;
return;
}
Node<T> A = new Node<T>();
Node<T> B = new Node<T>();
B = Head;
int j = 1;
while (B.Next != null&&j<i)
{
A = B;
B = B.Next;
j++;
}
if (j==i)
{
A.Next = B.Next;
}
}
/// <summary>
/// 计算链表元素个数
/// </summary>
/// <returns></returns>
public int GetLength()
{
Node<T> p = Head;
int length = 0;
while (p!=null)
{
p = p.Next;
length++;
}
return length;
}
/// <summary>
/// 判断链表是否为空
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
if (Head == null)
return true;
else
return false;
}
/// <summary>
/// 清空链表
/// </summary>
public void Clear()
{
Head = null;
}
/// <summary>
/// 获取当前位置的结点值
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public T GetNodeValue(int i)
{
if (IsEmpty()||i<1||i>GetLength())
{
Console.WriteLine("单链表为空或结点位置有误!");
return default(T);
}
Node<T> A = new Node<T>();
A = Head;
int j = 1;
while (A.Next!=null&&j<i)
{
A = A.Next;
j++;
}
return A.Data;
}
/// <summary>
/// 增加单链表插入的位置
/// </summary>
/// <param name="item"></param>
/// <param name="n"></param>
public void Insert(T item,int n)
{
if (IsEmpty()||n<1||n>GetLength())
{
Console.WriteLine("单链表为空或结点位置有误!");
return;
}
if (n==1)
{
Node<T> H = new Node<T>();
H.Next = Head;
Head = H;
return;
}
//========================== 取n结点的值 ===============
Node<T> A = new Node<T>();
Node<T> B = new Node<T>();
B = Head;
int j = 1;
while (B.Next != null && j < n)
{
A = B;
B = B.Next;
j++;
}
//end======================= 取n结点的值 ===============
if (j==n)
{
Node<T> C = new Node<T>(item);
A.Next = C;
C.Next = B;
}
}
}
以上代码只是个人当复习单链表类使用
参考目录:https://www.cnblogs.com/caokai520/p/4334453.html 感谢这位网友的分享
|