我已经实施了一个自定义链接列表,但我无法找到我预期的结果,因为它无法解决问题。
package LinkedList;
public class Node {
protected Node nextNode;
protected int data;
public Node(int data) {
this.data = data;
}
}
package LinkedList;
public class LinkedList {
private Node head;
public void insertLast(int data) {
Node new_node = new Node(data);
if(head == null) {
head = new_node;
}else {
Node n = head;
while(n.nextNode != null) {
n = n.nextNode;
}
n.nextNode = new_node;
}
}
public void insertFirst(int data) {
Node new_node = new Node(data);
if(head == null) {
head = new_node;
}else {
Node node = head;
head = new_node;
head.nextNode = node;
}
}
public void insertAt(int index,int data) {
int x = 1;
Node node = head;
while(node != null) {
if(index == 0) {
insertFirst(data);
break;
}else {
node = node.nextNode;
if( index == x ) {
Node new_node = new Node(data);
Node current = node;
node = new_node;
node.nextNode = current;
break;
}
x++;
}
}
}
public void print() {
Node node = head;
while(node != null) {
System.out.println(node.data);
node = node.nextNode;
}
}
}
package Test;
import LinkedList.*;
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertLast(100);
list.insertLast(200);
list.insertLast(300);
list.insertLast(400);
list.insertLast(500);
list.insertAt(1, 50);
list.print();
}
}
使用向特定位置添加元素时会出现此问题。在打印出结果时,元素不会被添加到列表中,我很难调试代码来解决问题。
答案 0 :(得分:1)
您在insertAt()
中的插入完全错过了新节点。您希望在两个节点之间添加元素,以便从node1 -> node2
更改为node1 -> new_node -> node2
。您需要将node1的下一个节点修改为新节点,并确保新节点指向node2。尝试这样的代码:
public void insertAt(int index,int data) {
//assumes index <= size of linked list
int curr = 1;
if(index < 0)
return;
if(index == 0){
insertFirst(data);
return;
}
Node currNode = head;
while( curr < index){
currNode = currNode.nextNode;
curr++;
}
Node newNode = new Node(data);
newNode.nextNode = currNode.nextNode;
currNode.nextNode = newNode;
}