HackerRank链表节点删除-一个测试案例失败,需要理解哪里出了问题。

huangapple go评论64阅读模式
英文:

Hacker rank linklist node deletion-one test case failing need to understand where is it going wrong

问题

class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert_node(self, node_data):
        node = SinglyLinkedListNode(node_data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node

        self.tail = node

def deleteNode(llist, position):
    if llist is None:
        llist = None
        return llist
    else:
        temp = llist
        index = 0
        while index < position - 1:
            temp = temp.next
            index += 1
        new_node = temp.next
        temp.next = new_node.next

    return llist

The provided code defines a singly linked list and a function deleteNode that deletes a node at the specified position. The issue you mentioned is related to not being able to use the self.tail variable outside the class. In this case, you can modify the SinglyLinkedList class to include a method for deleting a node, which would allow you to access self.tail:

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert_node(self, node_data):
        node = SinglyLinkedListNode(node_data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node

        self.tail = node

    def delete_node(self, position):
        if self.head is None:
            return

        if position == 0:
            self.head = self.head.next
            return

        current = self.head
        index = 0

        while current is not None and index < position - 1:
            current = current.next
            index += 1

        if current is None or current.next is None:
            return

        current.next = current.next.next

With this modification, you can create a SinglyLinkedList object and use the delete_node method to delete nodes, which will make it easier to handle the self.tail variable.

英文:
#!/bin/python3

import math
import os
import random
import re
import sys

class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert_node(self, node_data):
        node = SinglyLinkedListNode(node_data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node


        self.tail = node

def print_singly_linked_list(node, sep, fptr):
    while node:
        fptr.write(str(node.data))

        node = node.next

        if node:
            fptr.write(sep)

#
# Complete the &#39;deleteNode&#39; function below.
#
# The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
# The function accepts following parameters:
#  1. INTEGER_SINGLY_LINKED_LIST llist
#  2. INTEGER position
#

#
# For your reference:
#
# SinglyLinkedListNode:
#     int data
#     SinglyLinkedListNode next
#
#

def deleteNode(llist, position):
    # Write your code here
    if llist is None: 
        llist=None
        return llist
    else:
        temp=llist
        index=0
        while index&lt;position-1:
            temp=temp.next
            index+=1
        new_node=temp.next
        temp.next=new_node.next 
            
    return llist
            
        
        

if __name__ == &#39;__main__&#39;:
    fptr = open(os.environ[&#39;OUTPUT_PATH&#39;], &#39;w&#39;)

    llist_count = int(input())

    llist = SinglyLinkedList()

    for _ in range(llist_count):
        llist_item = int(input())
        llist.insert_node(llist_item)

    position = int(input())

    llist1 = deleteNode(llist.head, position)

    print_singly_linked_list(llist1, &#39; &#39;, fptr)
    fptr.write(&#39;\n&#39;)

    fptr.close()

Link: https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list/problem?isFullScreen=true

I was trying to solve this hacker rank challenge but only 1 of the test cases are failing, i'm not sure why is it failing can anyone point out the error?

Test case:

7
11
12
8
18
16
5
18
0

Expected o/p:

12 8 18 16 5 18

As the method is outside the class, hence i'm not able to use the self.tail veriable then it would have been easy

答案1

得分: 1

Your code does not work correctly when position is 0. In that case it acts as if position was 1 and removes the second node instead of the first. You'll have to deal with this case separately.

No problem, but:

  • llist=None is useless where you have it, because the if condition had just asserted that llist was already None

  • It is more pythonic to loop over a range than to have a while loop in which you increase a counter with += 1.

  • There is no need to use the new_node name (which is a strange name for a node that is about to be removed), as you can make the assignment to the next attribute directly.

  • After an if ... return there is no need to have an else block; you can save one level of indentation here.

  • The challenge guarantees that the list will not be empty, so in theory you don't need the first if condition. Still, I think it is a good habit to keep it in.

  • If position would be an index that is out of range, then your code would produce an error. This is not really a problem, because the challenge guarantees that there are no such test cases, but it is still a good habit to foresee such cases.

  • temp is not a very meaningful name. I'd suggest prev or previous to indicate that we aim to identify the node that precedes the node to remove.

Proposed code:

def deleteNode(llist, position):
    if not llist: # will not happen here, but good to have it
        return
    if position == 0:  # need to deal with this case separately
        return llist.next
    if llist.next:  # otherwise position is out of range
        prev = llist
        for _ in range(1, position):  # pythonic loop
            prev = prev.next
            if not prev.next:
                break  # position is out of range
        else:  # position is in range
            prev.next = prev.next.next             
    return llist
英文:

Your code does not work correctly when position is 0. In that case it acts as if position was 1 and removes the second node instead of the first. You'll have to deal with this case separately.

No problem, but:

  • llist=None is useless where you have it, because the if condition had just asserted that llist was already None

  • It is more pythonic to loop over a range than to have a while loop in which you increase a counter with += 1.

  • There is no need to use the new_node name (which is a strange name for a node that is about to be removed), as you can make the assignment to the next attribute directly.

  • After an if ... return there is no need to have an else block; you can save one level of indentation here.

  • The challenge guarantees that the list will not be empty, so in theory you don't need the first if condition. Still, I think it is a good habit to keep it in.

  • If position would be an index that is out of range, then your code would produce an error. This is not really a problem, because the challenge guarantees that there are no such test cases, but it is still a good habit to foresee such cases.

  • temp is not a very meaningful name. I'd suggest prev or previous to indicate that we aim to identify the node that precedes the node to remove.

Proposed code:

def deleteNode(llist, position):
    if not llist: # will not happen here, but good to have it
        return
    if position == 0:  # need to deal with this case separately
        return llist.next
    if llist.next:  # otherwise position is out of range
        prev = llist
        for _ in range(1, position):  # pythonic loop
            prev = prev.next
            if not prev.next:
                break  # position is out of range
        else:  # position is in range
            prev.next = prev.next.next             
    return llist

huangapple
  • 本文由 发表于 2023年3月31日 02:47:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定