(Medium #19) Remove Nth Node From End of List

Problem

Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?

My solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        out = None
        
        vallist = []
        while True:            
            vallist.append(head.val)
            head = head.next
            if head == None:
                break
        
        outlist = vallist[0:len(vallist)-n] + vallist[len(vallist)-n+1:]        
        for i in range(len(outlist)-1,-1,-1):
            temp = ListNode(outlist[i])
            temp.next = out
            out = temp
        return out            
Runtime: 32ms, Memory: 14MB

참고 (입력 만들기)

x_list=[1,2,3,4,5]
x = None
pre = ListNode(0)
for i in range(len(x_list)):
    pre = ListNode(x_list[i])
    pre.next = x
    print(id(x), id(pre))
    x = pre
    print(id(x), id(pre))         

댓글

  1. 안녕하세요 주렁님!
    주렁님 영상으로 이 악물고 코딩 배우고 있는 사람입니다!


    다름이 아니라
    이 문제를 파이썬 파일에 직접 돌려보았는데 에러가 나서요...
    혹시 봐주시면 정말 감사하겠습니다.

    우선 에러의 형태는 이러해요.
    AttributeError: 'list' object has no attribute 'val'

    head 가 ListNode 인 것을 눈치 못 채는 에러가 나고 있습니다. ㅠㅠ

    제가
    remove_nth_node.py파일에 적은 전체 파일은 이렇습니다.

    # https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/

    # Definition for singly-linked list.
    class ListNode:
    def __init__(self, x):
    self.val = x
    self.next = None

    class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
    out = None
    vallist = []
    while True:
    vallist.append(head.val)
    head = head.next
    if head == None:
    break
    outlist= vallist[0:len(vallist)-n] + vallist[len(vallist)-n+1:]

    for i in range(len(outlist)-1, -1, -1):
    temp = ListNode(outlist[i])
    temp.next = out
    out = temp
    return out

    if __name__ == "__main__":
    Solution.removeNthFromEnd('',head=[1,2,3,4,5],n=2)


    문제점이 어떤 건지
    너무 감이 안와서 이렇게 여쭤봅니다.

    주렁님 코드보면서 항상 수련하겠습니다.

    감사합니다.

    답글삭제
    답글
    1. 참고로 cmd 창에
      python remove_nth_node.py 라는 이름으로 돌렸습니다.

      삭제
    2. 댓글이 알림이 안와서 이제서야봤네요... 해결하셨나요?

      삭제

댓글 쓰기