Python header question from leetcode solution

  • Context: Python 
  • Thread starter Thread starter member 428835
  • Start date Start date
  • Tags Tags
    Python
Click For Summary

Discussion Overview

The discussion revolves around a Python implementation of a function to remove the nth node from the end of a linked list. Participants are examining the code structure, specifically the creation and manipulation of linked list nodes, and addressing errors encountered when passing a list instead of linked list nodes.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • Some participants explain that the first four lines of the code define a class for a linked list node, which includes a value and a pointer to the next node.
  • Others point out that the error arises because the code is attempting to treat a standard Python list as a linked list node, which leads to an AttributeError.
  • Several participants suggest that the input should be a linked list of ListNode objects rather than a list of integers, and propose creating the linked list from the array using loops.
  • One participant mentions the potential confusion in setting the 'next' property when nodes are added, suggesting the idea of a 'prior' property to simplify node linking.
  • Another participant discusses the possibility of using a recursive approach to solve the problem.
  • A later reply provides a code snippet demonstrating how to create a linked list from a list of values using a loop.

Areas of Agreement / Disagreement

Participants generally agree that the input to the function must be a linked list of ListNode objects, but there is no consensus on the best method to create this linked list or whether a single loop could be used effectively.

Contextual Notes

Limitations include the assumption that the input must be a linked list, and the unresolved question of whether a single loop can be used to create the linked list correctly.

Who May Find This Useful

Readers interested in linked list manipulation in Python, particularly those working on coding challenges or learning about data structures.

member 428835
Hi PF!

I am looking at the following code
Python:
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
    # Two pointers - fast and slow
    slow = head
    fast = head
    # Move fast pointer n steps ahead
    for i in range(0, n):
        if fast.next is None:
            # If n is equal to the number of nodes, delete the head node
            if i == n - 1:
                head = head.next
            return head
        fast = fast.next
    # Loop until fast node reaches to the end
    # Now we will move both slow and fast pointers
    while fast.next is not None:
        slow = slow.next
        fast = fast.next
    # Delink the nth node from last
    if slow.next is not None:
        slow.next = slow.next.next
    return head
if __name__ == "__main__" : 
    head = [1,2,3,4,5]
    n = 2
    print(removeNthFromEnd(head,n))
Can anyone tell me what the first 4 lines are doing? Also, when I execute this code I get the error
Code:
Traceback (most recent call last):
  File "a19_removeNthNode.py", line 32, in <module>
    print(removeNthFromEnd(head,n))
  File "a19_removeNthNode.py", line 13, in removeNthFromEnd
    if fast.next is None:
AttributeError: 'list' object has no attribute 'next'
Anyone know what's happening?
 
Technology news on Phys.org
The first four lines are creating a class called listnode that has a value and a pointer to the next listnode item. listnode is one node of a linked list.

in your program you are passing in an array object and the code is trying to treat it as a listnode. See line 27 and beyond. You need to create a listnode object from the array [,2,3,4,5] to pass into the removeNthNode()
 
  • Like
Likes   Reactions: FactChecker
Your code starting at line 27 needs to start by creating a list, one node at a time. Then it can try to remove nodes from that list.
 
  • Like
Likes   Reactions: jedishrfu
As already noted, this part doesn't work, starting from line 28:
Python:
head = [1,2,3,4,5]
n = 2
print(removeNthFromEnd(head,n))

The list above consists of integer values, but it needs to contain ListNode objects. You can do this by using a loop in which each iteration creates a ListNode instance, and then appends it to a list of these objects.
Be sure to set the val and next attributes for each ListNode instance. I did this using two separate loops.
 
  • Like
Likes   Reactions: FactChecker
Mark44 said:
Be sure to set the val and next attributes for each ListNode instance. I did this using two separate loops.
Because the next node does not exist when a node is first added, there is some confusion and the 'next' property can not be set. It seems as though it would be nice for a node to have a 'prior' property or to add nodes in reverse order. A 'prior' property would allow an added node to go back to the prior node and set its 'next' property. The 'prior' pointer to the latest added node would have to be saved somewhere in order to set it when another node is added.
 
FactChecker said:
Because the next node does not exist when a node is first added, there is some confusion and the 'next' property can not be set.
Right, and this is why I used two loops. The first one set the val attribute for each, and set the next attribute for each to None. The next loop set the next pointers appropriately, but with the last node's next pointer remaining at None.

I thought about how this might be done using just one loop, starting from the end node. Nothing came immediately to mind, though.
 
  • Like
Likes   Reactions: FactChecker
Thank you all for the great discussion!
 
  • Like
Likes   Reactions: member 428835
  • #10
Mark44 said:
I thought about how this might be done using just one loop, starting from the end node. Nothing came immediately to mind, though.
Python:
items = [1, 2, 3, 4, 5]
head = None
for value in reversed(items):
    head = ListNode(value, head)
 
  • Like
Likes   Reactions: member 428835 and jedishrfu

Similar threads

  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 34 ·
2
Replies
34
Views
5K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 0 ·
Replies
0
Views
2K