import org.w3c.dom.Node;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class LinkedList{
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.addFirst(2);
l.addFirst("c");
System.out.println(l);
}
private Node first;
private class Node {
public Object data;
public Node next;
}
public void addFirst(Object obj){
Node newNode = new Node();
newNode.data=obj;
newNode.next=first;
first=newNode;
}
}
在我看来,您已经实现了addFirst
方法,但是您需要实现一个toString()
方法,以便您可以打印出列表的内容。
例如:
@Override
public String toString() {
String s = "";
Node n = first;
while (n != null) {
s += n.data + "n";
n = n.next;
}
return s;
}
指纹:
C 2
public class LinkedList{
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.addFirst("c");
l.addFirst("7");
System.out.println(l);
}
private Node first;
static class Node {
String data;
Node next;
}
private void addFirst(String s){
Node newNode = new Node();
newNode.data=s;
newNode.next=first;
first= newNode;
}
}
// Is something wrong with addfirst method? Its still not working.