2011-10-06 22 views
1

我创建了一个基本节点链接列表,显示列表的大小(即: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

几件事情必须在我看来

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; 
+1

推倒这worked..Thanks的帮助。我做了这个确切的事情,但我改变了所有的字符串[],只有printnodes需要string []。谢谢 – TMan

+0

我非常欢迎 – Genjuro