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

C# LinkedList에서 특정 노드를 제거하는 방법 – Remove() 메서드 완벽 가이드

C#의 LinkedList<T>에서 지정된 노드를 제거하려면 Remove() 메서드를 사용합니다. 이 메서드는 전달된 값과 일치하는 첫 번째 노드를 연결 리스트에서 찾아 삭제하며, 성공적으로 제거되면 true, 해당 값이 존재하지 않으면 false를 반환합니다.

예제 1: 정수형 LinkedList에서 노드 제거하기

다음은 정수 타입의 LinkedList에서 특정 값을 가진 노드를 제거하는 예제입니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      LinkedList<int> list = new LinkedList<int>();
      list.AddLast(100);
      list.AddLast(200);
      list.AddLast(300);
      list.AddLast(400);
      list.AddLast(500);
      list.AddLast(300);
      list.AddLast(500);

      Console.WriteLine("LinkedList 요소...");
      foreach(int i in list) {
         Console.WriteLine(i);
      }

      LinkedListNode<int> val = list.FindLast(300);
      Console.WriteLine("지정된 값 = " + val.Value);

      list.Remove(500);

      Console.WriteLine("LinkedList 요소... 업데이트됨");
      foreach(int i in list) {
         Console.WriteLine(i);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

LinkedList 요소...
100
200
300
400
500
300
500
지정된 값 = 300
LinkedList 요소... 업데이트됨
100
200
300
400
300
500

위 예제에서 주목할 점은 리스트에 값 500이 두 개 존재하지만, Remove(500) 호출 시 맨 앞에서 처음 발견된 노드 하나만 제거되고 뒤쪽의 500은 그대로 남아 있다는 것입니다.

예제 2: 문자열 LinkedList에서 노드 제거하기

이번에는 문자열 타입의 LinkedList에서 배열 복사 후 특정 노드를 제거하는 방법을 살펴보겠습니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      LinkedList<string> list = new LinkedList<string>();
      list.AddLast("Mark");
      list.AddLast("David");
      list.AddLast("Harry");
      list.AddLast("John");
      list.AddLast("Kevin");

      string[] strArr = new string[5];
      list.CopyTo(strArr, 0);

      Console.WriteLine("배열로 복사한 후 LinkedList 요소...");
      foreach(string str in strArr) {
         Console.WriteLine(str);
      }

      list.Remove("Harry");

      Console.WriteLine("LinkedList 요소... 업데이트됨");
      foreach(string str in list) {
         Console.WriteLine(str);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

배열로 복사한 후 LinkedList 요소...
Mark
David
Harry
John
Kevin
LinkedList 요소... 업데이트됨
Mark
David
John
Kevin

예제에서는 CopyTo() 메서드로 LinkedList의 모든 요소를 문자열 배열에 복사한 뒤, Remove("Harry")를 호출하여 "Harry" 노드를 제거했습니다. 그 결과 리스트에서 해당 요소가 사라진 것을 확인할 수 있습니다.

핵심 정리

  • Remove(T value): 지정한 값과 일치하는 첫 번째 노드를 제거합니다.
  • Remove(LinkedListNode<T> node): 특정 노드 객체를 직접 전달하여 제거할 수도 있습니다.
  • Find() 또는 FindLast() 메서드로 노드를 검색한 후 제거하는 방식도 가능합니다.
  • 중복된 값이 있을 경우 Remove()는 맨 처음 발견된 노드만 삭제하고 나머지는 유지됩니다.