我是LinkedLists的新手。我们正在使用DoublyLinkedLists,我们必须执行一个名为addAfter的方法。所以我用谷歌搜索,却一无所获。节点类和变量初始化也由他在骨架中提供给我们,所以我马上想到,我是否缺少newInfo和afterThis的初始化?他就是这样描述addAfter ---
此方法将包含整数newInfo的新节点添加到包含整数afterThis的节点的下一个节点。如果afterThis之后没有包含整数的节点,请在最后插入新节点。如果存在多个包含afterThis整数的节点,请在列表中首次出现afterThis的旁边插入新节点。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
//import DoublyLinkedList.Node;
public class DoublyLinkedList {
public static class Node {
private int element;
private Node prev, next;
public Node(int e, Node p, Node n) {
element = e;
prev = p;
next = n;
}
public int getElement() {
return element;
}
public Node getPrev() {
return prev;
}
public Node getNext(){
return next;
}
public void setPrev(Node p) {
prev = p;
}
public void setNext(Node n) {
next = n;
}
}
/***************************************************************************************************************************/
public DoublyLinkedList(String fileName) throws IOException {
FileReader input = new FileReader(fileName); // this is where it reads the filenames HW4-A and myAnotherInput
BufferedReader myReader = new BufferedReader(input);
String line = "";
while ((line = myReader.readLine()) != null) {
int nextNumber = Integer.parseInt(line.trim());//needed trim or it kept throwing an error. Suggested by Liam.
// System.out.println(nextNumber);
addLast(nextNumber); // takes the number given by parseint and puts it last
System.out.println(nextNumber);
}
input.close();
}
private Node header;
private Node trailer;
private int size = 0;
public DoublyLinkedList() {
header = new Node(0, null, null);
trailer = new Node(0, header, null);
header.setNext(trailer);
}
public String toString() {
String toReturn = "";
Node current = header;
while (current != null) {
toReturn += current.getElement();//Credit to Liam (do not know last name, a CS student friend)
current = current.getNext();
if (current == null) {
break;
} else {
toReturn += " -> "; // Allows for -> to be put in between the numbers
}
}
return toReturn;
}
public void reverseList() {
// complete this method
}
public void addAfter(int newInfo, int afterThis) {
Node tmp = new Node(newInfo,header.next, trailer.prev);
tmp.prev = header.next;
header.next = header;
tmp.next = header.next;
if(afterThis == null)
newInfo.addLast();
}
public void negateList() {
// complete this method
}
public void addFirst(int e) {
Node tmp = new Node(e, header, null);
if(header != null ) {header.prev = tmp;}
header = tmp;
if(trailer == null) { trailer = tmp;}
size++;
}
public void addLast(int e) {
Node tmp = new Node(e, null, trailer);
if(trailer != null) {
trailer.next = tmp;
}
trailer = tmp;
if(header == null) {
header = tmp;
size++;
}
}
public int size() {
return size;//line 39 size
}
public boolean isEmpty() {
return size == 0;
}
}
这是我到目前为止所拥有的。同样,我只需要对addAfter进行一些指导。我很欣赏LinkedLists,因为它们证明了我很难掌握的知识。谢谢!