Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ลบอ็อบเจ็กต์ทั้งหมดจาก Stack ใน C#

Stack<T> มีเมธอด Clear() ลบสมาชิกทั้งหมด ทำให้ Count กลายเป็น 0 ใช้เมื่อต้องการรีเซ็ตสแท็กเพื่อใช้ใหม่

ตัวอย่างโค้ดที่ 1: สตริง

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Stack stack = new Stack();
        stack.Push("A");
        stack.Push("B");
        stack.Push("C");
        stack.Push("D");
        stack.Push("E");
        stack.Push("F");
        stack.Push("G");
        stack.Push("H");

        Console.WriteLine("Count of elements = " + stack.Count);
        Console.WriteLine("Elements in Stack...");
        foreach (string res in stack)
        {
            Console.WriteLine(res);
        }

        stack.Clear();
        Console.Write("Count of elements (updated) = " + stack.Count);
    }
}

ผลลัพธ์

Count of elements = 8
Elements in Stack...
H
G
F
E
D
C
B
A
Count of elements (updated) = 0

ตัวอย่างโค้ดที่ 2: จำนวนเต็ม 10 รายการ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Stack stack = new Stack();
        stack.Push(10);
        stack.Push(20);
        stack.Push(30);
        stack.Push(40);
        stack.Push(50);
        stack.Push(60);
        stack.Push(70);
        stack.Push(80);
        stack.Push(90);
        stack.Push(100);

        Console.WriteLine("Count of elements = " + stack.Count);
        Console.WriteLine("Elements in Stack...");
        foreach (int res in stack)
        {
            Console.WriteLine(res);
        }

        stack.Clear();
        Console.Write("Count of elements (updated) = " + stack.Count);
    }
}

ผลลัพธ์

Count of elements = 10
Elements in Stack...
100
90
80
70
60
50
40
30
20
10
Count of elements (updated) = 0

เมธอดหลักของ Stack<T>

MethodคำอธิบายComplexity
Push(T)เพิ่มที่บนสุดO(1) amortized
Pop()นำออกและคืนค่าบนสุดO(1)
Peek()ดูค่าบนสุด (ไม่ลบ)O(1)
Clear()ลบทั้งหมดO(n)
Contains(T)ตรวจสอบมีอยู่O(n)
ToArray()คัดลอกเป็น array (top to bottom)O(n)
CountจำนวนสมาชิกO(1)

ข้อสังเกต

  • Clear() ไม่คืนค่า - เพียงแค่ reset internal state
  • หลัง Clear() สแท็กว่างพร้อมใช้งานใหม่ทันที
  • Capacity อาจคงอยู่ (ไม่ลด) - ใช้ TrimExcess() (List) หรือสร้างใหม่
  • การวนลูป foreach ให้ลำดับ Top → Bottom (LIFO)

Non-generic Stack (Legacy)

System.Collections.Stack - ควรหลีกเลี่ยง ใช้ Stack<T> แทนเสมอ

Use Cases

  • Undo/Redo - Clear() เมื่อเริ่ม session ใหม่
  • Expression parsing - Clear() ระหว่าง parse หลายครั้ง
  • DFS/Backtracking - Clear() เมื่อ reset state
  • Browser history - Clear() เมื่อ clear history