繁体   English   中英

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

[英]Insert a Node at the Tail of a Linked List python HackerRank

它是一个非常简单的程序,用于在链接列表的末尾添加一个节点。 我不知道我在做什么错误。 与 hackerRank 的 exoected output 有关系还是我的代码有错误。 我正在尝试实现 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 == None并且something is not None而不是something != None
  • 您应该返回修改后的列表的头部。 您的函数不返回任何内容。

这个将通过 HackerRank 解释器为 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

这是答案——

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

节点类:

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

最后插入的方法是

 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. 然后我通过在 for 循环限制的 main 方法中调用 append function 来添加它们。
  3. 每次调用时,它都会将输入 integer 数据添加到节点并将其附加到列表中的前一个节点。
  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
        
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM