在Java中从用户输入列表创建BST

时间:2018-12-20 05:46:38

标签: java list input

我试图从一个提示用户输入的列表中创建一个二叉搜索树。手动为每个节点分配值时,代码可以正常工作。但是当我遍历输入每个值时,当我输出列表时,它为空并读取[0,0,0,0,0,0]。当提示您输入要输入多少个节点(例如7)时,系统会提示我输入7次值,然后该值结束。但是,当它输出列表时,列表为空。关于我在驱动程序中做错了什么的指针?然后,我将获取该列表并将其转换为BST。

enter code here
import java.util.Scanner;
import java.io.*; 
import java.util.*;

public class LinkedList { 

/* head node of link list */
static LNode head; 

/* Link list Node */
class LNode  
{ 
    int data; 
    LNode next, prev; 

    LNode(int d)  
    { 
        data = d; 
        next = prev = null; 
    } 
} 

/* A Binary Tree Node */
class TNode  
{ 
    int data; 
    TNode left, right; 

    TNode(int d)  
    { 
        data = d; 
        left = right = null; 
    } 
} 

/* This function counts the number of nodes in Linked List 
   and then calls sortedListToBSTRecur() to construct BST */
TNode sortedListToBST()  
{ 
    /*Count the number of nodes in Linked List */
    int n = countNodes(head); 

    /* Construct BST */
    return sortedListToBSTRecur(n); 
} 

/* The main function that constructs balanced BST and 
   returns root of it. 
   n  --> No. of nodes in the Doubly Linked List */
TNode sortedListToBSTRecur(int n)  
{ 
    /* Base Case */
    if (n <= 0)  
        return null; 

    /* Recursively construct the left subtree */
    TNode left = sortedListToBSTRecur(n / 2); 

    /* head_ref now refers to middle node,  
       make middle node as root of BST*/
    TNode root = new TNode(head.data); 

    // Set pointer to left subtree 
    root.left = left; 

    /* Change head pointer of Linked List for parent  
       recursive calls */
    head = head.next; 

    /* Recursively construct the right subtree and link it  
       with root. The number of nodes in right subtree  is  
       total nodes - nodes in left subtree - 1 (for root) */
    root.right = sortedListToBSTRecur(n - n / 2 - 1); 

    return root; 
} 

/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a  
   given Linked List */
int countNodes(LNode head)  
{ 
    int count = 0; 
    LNode temp = head; 
    while (temp != null) 
    { 
        temp = temp.next; 
        count++; 
    } 
    return count; 
} 

/* Function to insert a node at the beginging of  
   the Doubly Linked List */
void push(int new_data)  
{ 
    /* allocate node */
    LNode new_node = new LNode(new_data); 

    /* since we are adding at the begining, 
       prev is always NULL */
    new_node.prev = null; 

    /* link the old list off the new node */
    new_node.next = head; 

    /* change prev of head node to new node */
    if (head != null) 
        head.prev = new_node; 

    /* move the head to point to the new node */
    head = new_node; 
} 

/* Function to print nodes in a given linked list */
void printList(LNode node)  
{ 
    while (node != null)  
    { 
        System.out.print(node.data + " "); 
        node = node.next; 
    } 
} 

/* A utility function to print preorder traversal of BST */
void preOrder(TNode node)  
{ 
    if (node == null) 
        return; 
    System.out.print(node.data + " "); 
    preOrder(node.left); 
    preOrder(node.right); 
} 
//   public static  Object root(TNode root) {
//      return root;
//  }

/* Drier program to test above functions */
public static void main(String[] args) { 
      LinkedList lList = new LinkedList();
        Scanner scanner = new Scanner(System.in);
        // define how many nodes will be in the list
        System.out.println("How many nodes would you like to Enter:");
        int n = scanner.nextInt();
        int input[] = new int[n];
        // enter each node
        System.out.println("Enter the nodes:");
        for (int i = 0; i < n; i++)
        {
            // store values into the list
            int currInput = scanner.nextInt();
            lList.add(currInput);
            input[i] = currInput;
        }
        System.out.println("Given Linked List: ");
        System.out.println(Arrays.toString(input));

//      System.out.println("Given Linked List: ");
//      System.out.println(Arrays.toString(llists));
    //System.out.println(llists.length);
    /* Let us create a sorted linked list to test the functions 
       Created linked list will be 7->6->5->4->3->2->1 */
   // llist.push(7); 
   // llist.push(6); 
   // llist.push(5); 
   // llist.push(4); 
   // llist.push(3); 
   // llist.push(2); 
   // llist.push(1); 

    System.out.println("Given Linked List "); 

    //llist.printList(head); 

    /* Convert List to BST */
    TNode root = lList.sortedListToBST(); 
    System.out.println(""); 
    System.out.println("Pre-Order Traversal of constructed BST "); 
    lList.preOrder(root); 
    System.out.println("The root of the tree is: ");
    System.out.println(root.data);
}

private static int add(int nextInt) {
// TODO Auto-generated method stub
return 0;
} 

}

1 个答案:

答案 0 :(得分:0)

我认为您的命名约定使您难以理解代码。 尝试更改将用户输入从

添加到数组的代码
llists[i] = add(scanner.nextInt());

llists[i] = scanner.nextInt();

我认为您通过使用几乎相同的名称(即,用于数组和链接列表)混合了两种数据结构。您可以在以下位置找到add的用法:https://www.geeksforgeeks.org/java-util-linkedlist-add-method-in-java/

尝试使用此,

        // create a sorted linked list from user input
    LinkedList lList = new LinkedList();
    Scanner scanner = new Scanner(System.in);
    // define how many nodes will be in the list
    System.out.println("How many nodes would you like to Enter:");
    int n = scanner.nextInt();
    int input[] = new int[n];
    // enter each node
    System.out.println("Enter the nodes:");
    for (int i = 0; i < n; i++)
    {
        // store values into the list
        int currInput = scanner.nextInt();
        lList.add(currInput);
        input[i] = currInput;
    }
    System.out.println("Given Linked List: ");
    System.out.println(Arrays.toString(input));

此外,您介意为TreeNode添加定义。

PS,丹尼尔·罗杰(Daniel Roger)的代码也可以有其他解释,即add()函数,但是我试图将其分解为最简单的方法。