如何使用节点在链表中显示字符串

时间:2011-10-06 22:24:10

标签: java linked-list nodes

我创建了一个基本节点链表,用于显示列表的大小(即:0 - 9) 现在我想改变我要显示的名单列表。我对我需要改变什么以及会有什么不同感到困惑。名称将采用字符串格式。最后我要读一个txt文件中的名字列表。现在我只使用3个名字和测试数据。

       import java.util.*;

  public class Node {
public int dataitems; 
public Node next; 
Node front;

public void initList(){
    front = null;
}

public Node makeNode(int number){
    Node newNode;
    newNode = new Node();
    newNode.dataitems = number;
    newNode.next = null;
    return newNode;
}

public boolean isListEmpty(Node front){
    boolean balance;
    if (front == null){
        balance = true;
    }
    else {
        balance = false;
    }
    return balance;

}

public Node findTail(Node front) {
    Node current;
    current = front;
    while(current.next != null){
        //System.out.print(current.dataitems);
        current = current.next;

    } //System.out.println(current.dataitems);
    return current;
}

public void addNode(Node front ,int number){
    Node tail;
    if(isListEmpty(front)){
        this.front = makeNode(number);
    } 
    else {
        tail = findTail(front);
        tail.next = makeNode(number);
    }
}

public void printNodes(int len){

    int j;
    for (j = 0; j < len; j++){
        addNode(front, j);
    }  showList(front);
}

public void showList(Node front){
    Node current;
    current = front;
    while ( current.next != null){
        System.out.print(current.dataitems + " ");
        current = current.next;
    }
    System.out.println(current.dataitems);
}


public static void main(String[] args) {
     String[] names = {"Billy Joe", "Sally Hill", "Mike Tolly"}; // Trying to print theses names..Possibly in alphabetical order

    Node x = new Node();
     Scanner in = new Scanner(System.in);
        System.out.println("What size list? Enter Number: ");
    int number = in.nextInt();
     x.printNodes(number);
    } 

}

1 个答案:

答案 0 :(得分:1)

我认为必须改变一些事情

 public void printNodes(String[] nameList){

    int j;
    for (j = 0; j < nameList.length; j++){
        addNode(front, nameList[j]);
    }  showList(front);
}

你必须传递包含名称的数组

x.printNodes(names);

也改变了:

public void addNode(Node front ,String name){
    Node tail;
    if(isListEmpty(front)){
        this.front = makeNode(name);
    } 
    else {
        tail = findTail(front);
        tail.next = makeNode(name);
    }
}

和:

public Node makeNode(String name){
    Node newNode;
    newNode = new Node();
    newNode.dataitems = name;
    newNode.next = null;
    return newNode;
}

并且不要忘记将dateitem的类型更改为字符串:

      import java.util.*;

  public class Node {
public String dataitems;