Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# LinkedList Clear() 메서드 – 연결 리스트의 모든 노드 한 번에 삭제하기

C# LinkedList Clear() 메서드란?

C#에서 Clear() 메서드를 사용하면 LinkedList의 모든 요소를 한 번에 제거할 수 있습니다. 이 메서드를 호출하면 연결 리스트에 포함된 모든 노드가 삭제되고, 리스트의 Count 값은 0으로 초기화됩니다.

LinkedList 선언하기

먼저 다음과 같이 정수 배열을 기반으로 LinkedList를 생성해 보겠습니다.

int[] num = {30, 65, 80, 95, 110, 135};
LinkedList<int> list = new LinkedList<int>(num);

LinkedList 비우기

LinkedList의 모든 노드를 제거하려면 아래와 같이 Clear() 메서드를 호출하면 됩니다.

list.Clear();

전체 예제 코드

노드를 출력한 뒤 리스트를 비우고, 다시 순회하여 결과를 확인하는 전체 코드입니다.

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      int[] num = {30, 65, 80, 95, 110, 135};
      LinkedList<int> list = new LinkedList<int>(num);

      foreach (var n in list) {
         Console.WriteLine(n);
      }

      // 모든 노드 삭제
      list.Clear();
      Console.WriteLine("이제 LinkedList에는 노드가 없습니다...");

      foreach (var n in list) {
         Console.WriteLine(n);
      }
   }
}

실행 결과

Clear() 호출 후에는 더 이상 출력되는 노드가 없는 것을 확인할 수 있습니다.

30
65
80
95
110
135
이제 LinkedList에는 노드가 없습니다...

정리

Clear() 메서드는 LinkedList<T> 클래스에 정의되어 있으며, 실행 시간 복잡도는 O(n)입니다. 호출이 완료되면 리스트의 Count는 0이 되고, FirstLast 속성은 null을 반환합니다. 연결 리스트 전체를 초기화해야 할 때 간편하게 활용할 수 있는 메서드입니다.