2

Its a very simple program of adding a node at the end of a link list. I dont know what mistake I am doing. has it something to do with the exoected output of hackerRank or there's a mistake in my code. I m trying to implement the Python2

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node
def Insert(head, data):

    if (head.head == None):
        head.head = Node(data)
    else:
        current = head.head
        while (current.next != None) and (current.data == data):
                           current = current.next
        current.next = Node(data)

Heres a link to the question. https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list

8 Answers 8

8

If you have to add at the end of linklist then It's not needed to test current.data == data, Below code should be enough-

def Insert(head, data):

    if (head == None):
        head = Node(data)
    else:
        current = head
        while (current.next != None):
            current = current.next
        current.next = Node(data)
    return head

Also note that Python you don't need to use () after if and while.

Sign up to request clarification or add additional context in comments.

5 Comments

I keep on getting this error: Traceback (most recent call last): File "solution.py", line 83, in <module> head2 = Insert(head2,y[i]) File "solution.py", line 50, in Insert if (head.head == None): AttributeError: 'NoneType' object has no attribute 'head'
That means you are passing wrong head, Can i see your solution.py ?
This is all I have got in my Solution file. could you please take a look at link provided ?
@OjasKale I have checked the link and modified my answer with working code, Try this code now
Thanks a lot. @alokthakur
2

Your code has several problems:

  • head is either None or an instance of Node. Neither has a head attribute, so head.head makes no sense.
  • None is a singleton, so test something is None instead of something == None and something is not None instead of something != None.
  • You're supposed to return the head of the modified list. Your function doesn't return anything.

3 Comments

Could u please suggest a solution ? I know what am I suppose todo but I am not able to implement it. @Das-g
Giving you the finished solution would kinda defeat the purpose of hackerrank.com, wouldn't it?
I got your point. Thanks a lot. I needed to brush up the basics of linkd list. Thanks a lot for help.
2

This one will ran through HackerRank interpreter for python3

#print ('This is start of the function')
node = SinglyLinkedListNode(data)

if (head == None):
    head = node
else:
    current = head
    while (current.next != None):
        current = current.next
    current.next = node
return head

Comments

1

here's the answer -

#!/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

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

        node = node.next

        if node:
            fptr.write(sep)

def insertNodeAtTail(head, data): 
    item = SinglyLinkedListNode(data)
     
    if head is None:
        head = item 
    else:
        n = head
        
        while(n.next):
            n = n.next 
            
        n.next = item
         
    return head

Comments

0

Node Class:

class Node(object): def init(self, item): self.data = item self.next = None

def getdata(self):
    return self.data

def setdata(self, item):
    self.data = item

def getnext(self):
    return self.next

def setnext(self, item):
    self.next = item

and method to insert at the end is

 def insert(head, item):
    newNode = Node(item)
    newNode.setdata(item)
    current = head
    while current.getnext() != None:
        current = current.getnext()
    current.setnext(newNode)

Comments

0

for a separate recursive version:

def getTail(node):
    if node.next == None:
        return node
    return getTail(node.next)

def Insert(head, data):
    if head == None:
        return Node(data)
    tail = getTail(head)
    tail.next = Node(data)
    return head

Comments

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

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

# Implementation
def insertNodeAtTail(head, data):
    if head == None:
        head = SinglyLinkedListNode(data)
    else:
        current = head
        while current.next != None:
            current = current.next
        current.next = SinglyLinkedListNode(data)
    return head

Comments

0

OK so I just implemented the whole thing on the problem question in Hackerrank and passed all the test case checks and here is the solution I guess... there is just one slight issue is that I have it done in Java... but I'll try my best to explain it...

  1. First I have created a node for each addition to the tail.
  2. Then I have added them by calling out the append function in the main method for the limit of the for loop.
  3. With each call it adds the input integer data to the node and attaches it to the previous node in the list.
  4. Finally prints it.
  5. Kindly read the code, I have commented out the lines explaining what they do... don't worry I have tried to keep it as simple as possible for a python learner.

PS. Sorry, didn't see that this question was posted 6 years ago... well I just wanna keep this answer posted here so it might help another person out there in need.

GOOD LUCK AND KEEP LEARNING...

import java.io.*;
import java.util.*;

public class Solution {
    
    // class Solution is what should be called as the LINKEDLIST class but its ok
    
    Node head;  // declaring a head for the LL
    
    class Node {    // Node class
    
        int data;   // the .data variable
        Node ref;   // .ref aka .next 

        Node(int data) {    // constructor for initializing the values
        
            this.data = data;
            this.ref = null;
            
        }
    }
    
    public void append(int data) {  // i call 'to join at the end' as append
    
        Node newnode = new Node(data);  // new node creation
        
        if (head == null) {     // checking is head is null aka None in Py
            head = newnode;
            return;
        }
        
        Node curr = head;   // assigning head to a curr node ready for traversal
        
        while (curr.ref != null) {  // traversal begins
            curr = curr.ref;
        }                           // traversal ends
        
        curr.ref = newnode; // this is the last node where the join happens
        
    }
    
    public void p() {   // i name printing function as p()
    
        if (head == null) { // if head is null then print empty
            System.out.println("Empty");
            return;
        }
        
        Node curr = head;   // same thing - traversal begins here
        
        while (curr != null) {
            System.out.println(curr.data);
            curr = curr.ref;
        }   // by now all data values have been printed out already
        
    }

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);    // scanner class for input
        
        Solution l = new Solution();    // object creating for LL as Solution class name
        
        int numberOfNodes = sc.nextInt();   // input for number of NODEs in LL
        
        for (int i = 0; i < numberOfNodes; i++) {   // loop for .data values
        
            int data = sc.nextInt();    
            l.append(data); // function append call for each (i)
            
        }
        
        l.p();  // finally print func call to display output LL
        
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.