java 链表 插入_写了个Java的单链表,在指定位置插入时出现问题,不知道错在哪...

写了个Java的单链表,在指定位置插入时出现问题,不知道错在哪

在学数据结构 Java 版的,学到单链表,把自己搞蒙了

相关代码

/**

节点

@author huaian

*

*/

public class Node {

private Node node;

// node data

int data;

// next node

Node nextNode;

// node size

static int size = 0;

public Node() {

super();

}

public Node(int data) {

super();

this.node = this;

this.data = data;

size++;

}

/**

* 追加节点

*

* @param node 待添加的node

*/

public Node append(Node node) {

// 获取当前节点

Node currentNode = this.node;

while (true) {

// 获取下一个节点

Node nextNode = currentNode.nextNode;

// 判断是否是最后一个节点

if (nextNode == null) {

break;

}

currentNode = nextNode;

}

// 添加节点

currentNode.nextNode = node;

size++;

return this;

}

/**

* 往指定位置添加节点

* @param index

* @param newNode

* @return

*/

public Node add(int index, Node newNode) {

Node headNode = this.node;

Node currentNode = headNode;

Node preNode = null;

// 索引越界或者当前节点不存在则抛出异常

if (index > size || currentNode == null || index < 0) {

System.out.println("size = " + size);

throw new IndexOutOfBoundsException(index);

}

int count = 0;

// 找到待删除节点的前一个节点

while (!currentNode.isLast() && count < index) {

preNode = currentNode;

currentNode = currentNode.nextNode;

count++;

}

if (preNode == null) {

headNode = newNode;

headNode.nextNode = currentNode;

this.nextNode = headNode;

} else {

preNode.nextNode = newNode;

preNode.nextNode.nextNode = headNode;

this.node = preNode;

}

size++;

return node;

}

/**

* 删除指定索引下标的元素

* @param index 索引

* @return 新的链表

*/

public Node remove(int index) {

Node headNode = this.node;

Node currentNode = headNode;

Node preNode = null;

// 索引越界或者当前节点不存在则抛出异常

if (index > size || index <= 0) {

throw new IndexOutOfBoundsException(index);

}

int count = 1;

// 找到待删除节点的前一个节点

while (!currentNode.isLast() && count < index) {

preNode = currentNode;

currentNode = currentNode.nextNode;

count++;

}

if (preNode == null && index == count) {

headNode = currentNode.nextNode;

} else {

preNode.nextNode = currentNode.nextNode;

}

this.node = headNode;

size--;

return this.node;

}

/**

* 获取下一个节点

*

* @return 下一个节点

*/

public Node next() {

return this.nextNode;

}

/**

* 获取当前节点的数据

*

* @return 节点数据

*/

public int getData() {

return this.data;

}

/**

* 判断当前节点是否是最后一个节点

*

* @return 是否为最后一个节点

*/

public boolean isLast() {

return nextNode == null;

}

/**

* 链表节点数

*

* @return 节点数

*/

public int size() {

return size;

}

/**

* 判空

*

* @return 是否为空链表

*/

public boolean isEmpty() {

return size == 0;

}

}

当单链表中有数据 >= 4条时,使用 add(int index, new Node(5)) 插入节点时候时候,位置不对,其他数字不存在问题。求解答。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值