【leetcode】19. 연결리스트의 맨 아래 N번째 노드를 삭제한다.

주제

연결된 목록을 제공하고 연결 목록의 맨 아래에서 n번째 노드를 삭제하고 연결 목록의 헤드 노드를 반환합니다.
예 1:
여기에 이미지 설명을 삽입하세요.

욕조: head = [1,2,3,4,5], n = 2
탈출: [1,2,3,5]
예시 2:

욕조: head = [1], n = 1
탈출:[]
예시 3:

욕: head = [1,2], n = 1
욕:[1]

코드 작성

해당 위치에서 직접 연결리스트 작업 수행

class Solution {
    
    
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    
    
        if(head==nullptr){
    
    
          return head;
        } 
        
        ListNode *pre = nullptr;
        ListNode *saveHead = head; 
        int len = GetListLen(head);
        int i = 0;
        while(head!=nullptr){
    
        
          if(n ==len){
    
    
            if(pre==nullptr){
    
    
              return head->next;
            }
            if(head==nullptr){
    
    
              pre->next = nullptr;
            }else{
    
    
              pre->next = head->next;
            } 
            break;
          }
          len--;
          pre = head;
          head = head->next;
        }

        return saveHead;
    }

    int GetListLen(ListNode* head){
    
    
      int len = 0;
      while(head!=nullptr){
    
    
        len++;
        head = head->next;
      }

      return len;
    }
};

추천

출처blog.csdn.net/qq_41094072/article/details/134248866