LeetCode - 19. Remove Nth Node From End of List

2022. 7. 16. 23:32STUDY/LeetCode

반응형

HA..... 

이거 Two Pointer Category 라고..... ㅠㅠ 이 빠가사리야 (Po자책중wer)


Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

 

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Follow up: Could you do this in one pass?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode* H1;
    struct ListNode* H2;
    H1 = head;
    H2 = head;
    for(int i = 0; i < n; i++) {
        H1 = H1->next;
        if(!H1) return head->next;
    }
    while(H1->next) {
        H2 = H2->next;
        H1 = H1->next;
    }
    H2->next = H2->next->next;
    return head;
}

ㅎㅅㅎ 쥐니엇스..

H1로 우선 n만큼의 노드 count 를 깎아주고, 

H2랑 H1랑 같이 돌려서 H2를 total_list_count - n 위치까지 도달 시킨다. 

그담에 H2->next 를 H2->next->next 위치로 이동시켜 node 삭제.....

 

 

 

728x90
반응형

'STUDY > LeetCode' 카테고리의 다른 글

LeetCode - 240. Search a 2D Matrix II  (0) 2022.07.24
LeetCode - 733. Flood Fill  (0) 2022.07.17
LeetCode - 876. Middle of the Linked List  (0) 2022.07.16
LeetCode - Reverse Words in a String III  (0) 2022.07.16
LeetCode 189. Rotate Array  (4) 2022.07.08