/// <summary> /// 栈的遍历 /// </summary> public void Print() { string info = ""; LinkStackNode p = head.next; if (p == null) { info = "该栈是一个空栈"; } else { while (p != null) { info += p.data + " "; p = p.next; } } Console.WriteLine(info); //LinkStackNode current = new LinkStackNode(); //current = head.next; //while (current != null) //{ // Console.WriteLine(current.data); // current = current.next; //} }
/// <summary> /// 入栈操作 /// </summary> /// <param name="data">入栈的数据</param> public void Push(object data) { LinkStackNode current = new LinkStackNode(); current.data = data; current.next = head.next; head.next = current; count++; //元素个数加一 }
/// <summary> /// 获取栈底元素 /// </summary> /// <returns></returns> public object GetTail() { LinkStackNode newHead = head; LinkStackNode current = head.next; while (current.next != null) { current = current.next; } return(current.data); }
/// <summary> /// 将链栈的元素存入到可枚举的列表中 /// </summary> /// <returns>返回可枚举数据</returns> public IEnumerable <object> ToEnumerable() { List <object> toList = new List <object>(); LinkStackNode current = head.next; while (current != null) { toList.Add(current.data); current = current.next; } return(toList); }
/// <summary> /// 取得栈顶元素 /// </summary> /// <returns>返回值为栈顶节点的值</returns> public object GetTop() { if (head.next == null) { return("该栈为一个空栈,不存在栈顶元素!"); } else { LinkStackNode current = head.next; return(current.data); } }
/// <summary> /// 出栈操作 /// </summary> public void Pop() { if (head.next == null) { throw new Exception("该栈已经是空栈了,不能进行出栈操作!"); } else { LinkStackNode current = head.next; head.next = current.next; current = null; count--; } }