大家好我想知道如何在链表中显示所有节点。继承了我到目前为止的代码。 Manager类应该操作列表。 movieNode类为电影创建新的列表节点。我知道我也必须使用其他东西,但我只想尝试让列表的第一个元素显示给初学者。
public class Manager {
MovieNode head;
public Manager (){
head=null;
}
public void Add (MovieNode data) {
if (head==null){
head=data;
}
}
public void Display () {
int i=1;
MovieNode temp=head;
System.out.println("Displaying Movies");
while (head!=null) {
System.out.println(temp.getData().getName());
head=null;
}
}
}
还有,MovieNode类的代码
public class MovieNode {
private Movie data;
private MovieNode next;
public MovieNode (){
data=null;
next=null;
}
public MovieNode (Movie data){
setData(data);
}
public void setData (Movie data){
this.data=data;
}
public Movie getData (){
return data;
}
}
答案 0 :(得分:1)
希望这会帮助您入门。以下是一些提示:
经理类
head
变量并且您没有将任何其他信息传递给构造函数data
并在add方法中创建节点head
开始,然后检查列表中是否有节点next
。如果您不需要实现此自定义方法,我建议将该类实现为Iterable。可以在here MovieNode类
data
的构造函数并设置私有变量next
变量的getter和setter才能保存列表结构并遍历列表toString()
实现将允许直接打印此类的实例,如displayAllMovies()
方法电影课
title
,但您可以根据您的规格进行扩展。以下是代码:
public class Manager {
MovieNode head = null;
public void addMovie(Movie data) {
MovieNode newNode = new MovieNode(data);
if (head == null) {
head = newNode;
} else {
newNode.setNext(head);
head = newNode;
}
}
public void addMovieInOrder(Movie data) {
MovieNode newNode = new MovieNode(data);
if (head == null) {
head = newNode;
} else {
MovieNode higher = head;
MovieNode lower = null;
// find the right position for newNode
while(higher != null){
if(newNode.compareTo(higher) > 0){
lower = higher;
higher = higher.getNext();
}
else break;
}
newNode.setNext(higher);
if(higher == head) head = newNode; //inserting as head
else lower.setNext(newNode);
}
}
public void displayAllMovies() {
MovieNode node = head;
if (node == null) {
System.out.println("The list is empty!");
}
do {
System.out.println(node.getData());
node = node.getNext();
} while (node != null);
}
public static void main(String[] args) {
Manager manager = new Manager();
manager.addMovieInOrder(new Movie("ddd"));
manager.addMovieInOrder(new Movie("ccc"));
manager.addMovieInOrder(new Movie("aaa"));
manager.addMovieInOrder(new Movie("bbb"));
manager.displayAllMovies();
}
}
电影节点类:
public class MovieNode implements Comparable<MovieNode> {
private Movie data;
private MovieNode next = null;
public MovieNode(Movie data) {
this.data = data;
}
public void setData(Movie data) {
this.data = data;
}
public Movie getData() {
return data;
}
public void setNext(MovieNode node) {
this.next = node;
}
public MovieNode getNext() {
return next;
}
@Override
public String toString() {
return data.toString();
}
@Override
public int compareTo(MovieNode otherMovieNode) {
return data.compareTo(otherMovieNode.getData());
}
}
电影课:
public class Movie implements Comparable<Movie> {
private String title;
public Movie(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
@Override
public int compareTo(Movie otherMovie) {
return title.compareTo(otherMovie.title);
}
}