java单链表的添加、插入、删除

package nodelist;


public class LinkListTest {

public Node head = new Node();// 定义一个头节点


public LinkListTest() {

}


/**

* 添加一个节点

* @param data

*/

public void addNode(int data) {

Node node = new Node(data);

Node temp = head;

while (temp.next != null) {

temp = temp.next;

}

temp.next = node;

}


/**

* 插入某位置节点

* @param index

* @param node

*/

public void insertNodeByIndex(int index, Node node) {

if (index < 1 || index > getListLength()) {

System.out.println("插入位置不合法");

return;

}

Node temp = head;

int length = 1;// 记录光标位置

while (temp.next != null) {

if (index == length) {

// 找到要插入的位置,进行插入操作,

node.next = temp.next;

temp.next = node;

} else {

temp = temp.next;

}

length++;

}


}


/**

* 删除某位置的节点

* @param index

*/

public void deleteNodeByIndex(int index) {

if (index < 1 || index > getListLength()) {

System.out.println("删除位置不合法");

}

Node temp = head;

int length = 1;

while (temp.next != null) {

if (index == length) {

temp.next = temp.next.next;

return;

} else {

temp = temp.next;

}

length++;

}

}


public int getListLength() {

int length = 0;

Node temp = head;

while (temp.next != null) {

length++;

temp = temp.next;

}

return length;

}


/**

* 查找所有的节点

*/

public void displayAllNodes() {

Node temp = head;

while (temp.next != null) {

temp = temp.next;

System.out.println(temp.data);

}

}


/**

* @param args

*/

public static void main(String[] args) {

LinkListTest list = new LinkListTest();

list.addNode(1);

list.addNode(2);

list.addNode(3);

list.insertNodeByIndex(1, new Node(10));


list.displayAllNodes();

System.out.println("--------------");

list.deleteNodeByIndex(1);

list.displayAllNodes();

// System.out.println(list.getListLength());

}


}

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值