我正在用java做链表实现。特别是,在执行插入操作时,如果给定的索引大于链表的长度,我必须将该值追加到链表中。尽管我已经为此编写了代码,但事情并没有这样发生。
为了调试这个,我添加了用于打印链接列表的行。我可以在插入函数中的条件 if(index >= this.length())
之前打印列表,但无法在条件内的行中打印链接列表。
package com.learning.algorithms.LinkedList;
public class Node {
int data;
Node next;
public Node() {
}
public Node(int i) {
this.data = i;
this.next = null;
}
}
package com.learning.algorithms.LinkedList;
public class LinkedList {
Node head;
Node tail;
public LinkedList() {
this.head = new Node();
this.tail = this.head;
}
public LinkedList(int value) {
this.head = new Node();
this.head.data = value;
this.head.next = null;
this.tail = this.head;
}
public LinkedList append(int value) {
Node newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
return this;
}
public void printList() {
Node useNode = this.head;
while(useNode!=null)
{
System.out.println(useNode.data);
useNode = useNode.next;
}
//print(useNode);
}
private void print(Node useNode) {
if(useNode!=null)
{
System.out.println(useNode.data);
print(useNode.next);
}
}
public LinkedList prepend(int i) {
Node newNode = new Node(i);
newNode.next = this.head;
this.head = newNode;
return this;
}
public LinkedList insert(int index, int value) {
if(index == 0)
{
this.prepend(value);
return this;
}
this.printList();
if(index >= this.length())
{
System.out.println("inside");
this.printList();
this.append(value);
return this;
}
Node nodeJustBeforeGivenIndex = this.head;
// getting node just before given index using while loop
while(index>1)
{
nodeJustBeforeGivenIndex = nodeJustBeforeGivenIndex.next;
index--;
}
// make an insert
Node newNode = new Node(value);
newNode.next = nodeJustBeforeGivenIndex.next;
nodeJustBeforeGivenIndex.next = newNode;
return this;
}
private int length() {
int counnt = 0;
if(this.head !=null ) {
while(this.head !=null )
{
this.head = this.head.next;
counnt++;
}
}
return counnt;
}
}
package com.learning.algorithms.LinkedList;
public class LinkedListImplementation {
public static void main(String[] args)
{
LinkedList list = new LinkedList(10);
list.append(5);
list.append(16);
list.prepend(1);
list.insert(0, 15);
list.insert(10, 222);
list.printList();
}
}
运行此实现类的控制台输出:
15
1
10
5
16
inside
最佳答案
您不应修改 length 方法内的 head 值。
这将解决它:
private int length() {
int counnt = 0;
Node iter = this.head;
while(iter !=null )
{
iter = iter.next;
counnt++;
}
return counnt;
}
仅注释插入内的两个打印状态,输出为:
inside
15
1
10
5
16
222
关于java - 为什么我无法将元素插入到我的链表实现中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61064542/