感谢您花时间阅读本文,我目前正在学习 Java 课程,教授告诉我们,理解链接的一个好做法是制作一个双向链表。我制作了一个单链表,但我无法将其转换为双链表。我遇到的问题是我试图在列表末尾添加一个数字,但是当我尝试在末尾添加一个新数字时,它只显示该数字而不是其他数字。我想我只是在创建一个新列表并显示它,但我不确定。一个代码示例将不胜感激。
正常添加代码:
public void add(int element){
Node n = new Node();
n.setItem(element);
n.setNext(head);
n.setBefore(null);
if(head != null) {
head.setBefore(n);
}
head = n;
}
添加到最后的代码:
public void addLast(int element) {
Node currentNode = head;
currentNode.setItem(element);
currentNode.setBefore(tail);
currentNode.setNext(null);
tail = currentNode;
}
完整代码:
public class DoubleLink {
private Node head;
private Node tail;
//Methods
//Constructors
public DoubleLink(){
head = null;
tail = null;
}
public void add(int element){
Node n = new Node();
n.setItem(element);
n.setNext(head);
n.setBefore(null);
if(head != null) {
head.setBefore(n);
head = n;
}
public void display(){ //LIST TRAVERSAL!
// Reference traversal
//Needed an interatior
Node currentNode = head;
while(currentNode != null){
System.out.print(currentNode.getItem()+ " ");
currentNode = currentNode.getNext();
}
System.out.println();
}
public int search(int element){
int position = 0;
Node currentNode = head;
while(currentNode != null){
if(currentNode.getItem() == element){
return position;
}
position++;
currentNode = currentNode.getNext();
}
return -1;
}
public void insert(int element, int position){
int currentposition = 0;
Node currentNode = head;
//Traverse to the right position
while(currentposition < position-1){
currentposition++;
}
Node n = new Node();
n.setItem(element);
n.setNext(currentNode.getNext());
currentNode.setNext(n);
//The previous number connecting to the new number
currentNode = tail;
}
public void remove(int position){
int currentposition = 0;
Node currentNode = head;
//Traverse to the right position
while(currentposition < position-1){
currentposition++;
}
Node dyingNode = currentNode.getNext();
currentNode.setNext(dyingNode.getNext());
}
public void addLast(int element) {
Node nodeToInsert = new Node();
nodeToInsert.setItem(element);
nodeToInsert.setBefore(tail);
nodeToInsert.setNext(null);
if(tail != null)
tail.setNext(nodeToInsert); //link the list
tail = nodeToInsert; //now the tail is the new node i added
if(head == null) // if the list has no elements then set the head
head = nodeToInsert;
}
public static void main(String[] args) {
DoubleLink l = new DoubleLink();
l.add(1);
l.add(2);
l.add(3);
l.display();
l.addLast(99);
l.display();
}
}
节点类:
public class Node {
//Data
private int item;
private Node next;
private Node before;
//Methods
public int getItem(){
return item;
}
public void setItem(int item){
this.item = item;
}
public Node getNext(){
return next;
}
public void setNext (Node next){
this.next = next;
}
public Node getBefore(){
return before;
}
public void setBefore(Node before){
this.before = before;
}
}