在链表python HackerRank的尾部插入一个节点



这是一个非常简单的程序,在链接列表的末尾添加一个节点。我不知道我犯了什么错误。它与hackerRank的输出有关,或者我的代码中有错误。我正在尝试实现 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)

这是问题的链接。https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list

如果一定要在链接列表末尾添加那么就不需要测试current.data == data了,下面的代码应该足够了——

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

另请注意,Python 不需要在 if 和 while 之后使用 ()

您的代码有几个问题:

  • head要么是None,要么是Node的实例。也没有 head属性,所以head.head没有意义。
  • None是单例,因此请测试something is None而不是something == Nonesomething is not None而不是something != None
  • 您应该返回修改列表的头部。您的函数不返回任何内容。

这个将通过 python3 的 HackerRank 解释器运行

#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
这是

答案 -

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

节点类:

类节点(对象): def init(self, item): 自我数据 = 项目 self.next = 无

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

最后插入的方法是

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

用于单独的递归版本:

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
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
好的,

所以我只是在Hackerrank中实现了整个问题并通过了所有测试用例检查,我想这是解决方案...只有一个小问题是我用 Java 完成了它......但我会尽力解释它...

  1. 首先,我为尾部的每个添加创建了一个节点。
  2. 然后,我通过在 main 方法中调用 append 函数来添加它们,以限制 for 循环。
  3. 每次调用时,它都会将输入整数数据添加到节点,并将其附加到列表中的前一个节点。
  4. 最后打印出来。
  5. 请阅读代码,我已经注释掉了解释它们作用的行......别担心,我试图让 python 学习者尽可能简单。

对不起,没看到这个问题是6年前发布的...好吧,我只想把这个答案贴在这里,这样它可能会帮助另一个有需要的人。

祝你好运,继续学习...

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
        
    }
}

相关内容

最新更新