java单链表 提供增删改查_【Java】单链表的增删改查

public class MyLinkedList {

static class ListNode {

int val;

ListNode next;

public ListNode(int val){

this.val = val;

}

}

ListNode head;// 头结点

ListNode tail;// 尾结点

int size;

public MyLinkedList(){

head = null;

tail = null;

size = 0;

}

// 插入方法

public void insert(int position, int number){

if(position > size){

return;

}

ListNode newNode = new ListNode(number);

// 要插入的位置是0(即为头部)

// case 1 : 头部插入

if(position == 0){

newNode.next = head;

head = newNode;

// 判断尾结点是不是null, 如果是null说明这是插入的第一个元素

if(tail == null){

tail = newNode;

}

size++;

}

// case 2 : 尾部插入

else if(position == size){

this.append(number);

}

// case 3 : 中间插入

else {

// 找到插入位置之前的节点

ListNode prev = head;

for (int i = 0; i < position - 1; i++) {

prev = prev.next;

}

ListNode next = prev.next;

newNode.next = next;

prev.next = newNode;

size++;

}

}

public void append(int number){

ListNode newNode = new ListNode(number);

if(tail == null){

tail = newNode;

} else {

tail.next = newNode;

tail = newNode;

}

size++;

}

// 删除

public void delete(int number){

// 删除头结点

if(head != null && head.val == number){

head = head.next;

size--;

// 如果size==0 说明只有一个元素

if(size == 0) {

tail = head;

}

}

else

{

ListNode prev = head;

ListNode current = head;

while(prev != null && current != null){

if(current.val == number){

if(current == tail){

tail = prev;

}

prev.next = current.next;

size--;

return;

}

prev = current;

current = current.next;

}

}

}

// 查找 返回位置

public int search(int number){

ListNode current = head;

for (int i = 0; current != null; i++) {

if(current.val == number){

return i;

}

current = current.next;

}

return -1;

}

// 修改

public int update(int oldValue, int newValue){

ListNode current = head;

for (int i = 0; current != null; i++) {

if(current.val == oldValue){

current.val = newValue;

return i;

}

current = current.next;

}

return -1;

}

public static void main(String[] args) {

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值