根据有序表L2表的值删除L1表的节点

本文介绍了一种基于两个有序链表的算法,该算法通过遍历链表L1并利用数组L2作为指示哪些节点应该被删除的依据,最终实现了从L1中删除指定节点的功能。示例中给出了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:根据有序表L2的值删除链表L1的节点。比如:L1 = {A,B,C,D,E,F}, L2={1,2,3,10}

那么删除之后L1={A,E,F},因为节点10不存在


下面是节点类(也为了其他测试的用途,实现了一个copy接口)


public class Node implements Cloneable {
public String value;
public Node next;

public Node(String value, Node next) {
this.value = value;
this.next = next;
}


@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}



下面是主函数方法~

其中L2我采用了一个数组来存储


public class MinusList {
public static void main(String[] args) {
Node a0 = new Node("a0",null);
Node a1 = new Node("a1",null);
Node a2 = new Node("a2",null);
Node a3 = new Node("a3",null);
Node a4 = new Node("a4",null);
Node a5 = new Node("a5",null);
Node a6 = new Node("a6",null);

a0.next = a1;
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
a5.next = a6;

int[] array = {2,4,8};

Node head = a0;
Node t = head;
Node t2;
for(int i=0; i < array.length; i++) {
int steps = array[i];
if(i != 0) {
steps = array[i] - array[i-1];
}
for(; (steps > 1) && (t != null); steps--) { //让t指向目标节点的上一个节点
t = t.next;
}
if(t != null) {
t2 = t.next;
t.next = t.next.next;
t2 = null;
}
}

//print all nodes
t = head;
while(t != null) {
System.out.print(t.value + " ");
t = t.next;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值