관리 메뉴

솜씨좋은장씨

[leetCode] 19. Remove Nth Node From End of List (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 19. Remove Nth Node From End of List (Python)

솜씨좋은장씨 2020. 11. 16. 00:05
728x90
반응형

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

Follow up: Could you do this in one pass?

 

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

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        answerList = ListNode()
        
        answer = None
        
        linked_list = []
        
        cnt = 0
        
        
        while True:
            if head == None:
                break
                
            value = head.val
            
            linked_list.append(value)
            
            head = head.next
            
        linked_list_len = len(linked_list)
        
        check_num = linked_list_len - n
        
        check_flag = False
        

        for i in range(len(linked_list)):
            if i == check_num:
                continue
            elif check_flag == False:
                answerList = ListNode(linked_list[i])
                check_flag = True
            else:
                new_node = ListNode(linked_list[i])
                currNode = answerList
                while currNode.next != None:
                    currNode = currNode.next
                currNode.next = new_node
        if check_flag == False:
            return answerList.next
                
        return answerList

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments