单链表的末尾添加结点操作
程序代码:
public void Append(T item) { Node<T> q = new Node<T>(item); Node<T> p = new Node<T>(); if (head == null) { head = q; return; } p = head; while (p.Next != null) { p = p.Next; } p.Next = q; }
using System; public class Node<T> { private T m_Data; private Node<T> m_Next; public Node(T nData, Node<T> nNext) { m_Data = nData; m_Next = nNext; } public Node(T nData) { m_Data = nData; m_Next = null; } public Node(Node<T> nNext) { m_Data = default(T); m_Next = nNext; } public Node() { m_Data = default(T); m_Next = null; } public T GetData { get { return m_Data; } set { m_Data = value; } } public Node<T> GetNext { get { return m_Next; } set { m_Next = value; } } } public interface IList<T> { void Inserter(T nElem);//插入元素 void Reverse();//逆置 void Print();//输出 } public class CList<T> : IList<T> { private Node<T> m_Head;//单链表的头引用 public Node<T> GetHead { get { return m_Head; } set { m_Head = value; } } public CList() { m_Head = new Node<T>();//头结点 } public void Inserter(T nElem)//插入元素 {//末尾插入 Node<T> nTmp = m_Head; while (null != nTmp.GetNext) { nTmp = nTmp.GetNext; } nTmp.GetNext = new Node<T>(nElem); } public void Reverse()//逆置 { Node<T> nTmp = m_Head.GetNext; m_Head.GetNext = null; while (null != nTmp) { Node<T> Tmp = nTmp.GetNext; nTmp.GetNext = m_Head.GetNext; m_Head.GetNext = nTmp; nTmp = Tmp; } } public void Print()//输出 { Node<T> nTmp = m_Head.GetNext; while (null != nTmp) { Console.Write("{0} ", nTmp.GetData); nTmp = nTmp.GetNext; } Console.WriteLine(); } } public class App { public static void Main() { CList<int> list = new CList<int>(); int[] nArray = new int[] { 1,2,3,4,5,6}; for (int i = 0; i < nArray.Length; ++i) { list.Inserter(nArray[i]); } list.Print(); list.Reverse(); list.Print(); } }