新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

关于链表:删除指定元素、在指定位置后插入或删除元素-创新互联

说明:思路中写的是伪代码,为了表达意思。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名网站空间、营销软件、网站建设、阜康网站维护、网站推广。

一,删除链表中与val相等的结点

需要两个结点 cur和prev(作为cur的前驱结点)
遍历整个链表,与给定的val作比较,
如果相等:prev.next=cur.next;
如果不相等:cur=cur.next;

二、在指定POS后插入、删除结点
插入:pos.next=node;
node.next=pos.next;
删除:pos.next=pos.next.next

代码如下:

```class Node {
int val;
Node next = null;

Node(int val) {
    this.val = val;
}

public String toString() {
    return String.format("Node(%d)", val);
}

}

class Solution {
public Node removeElements(Node head, int val) {
Node result = null;
Node last = null; // 记录目前 result 中的最后一个结点

Node cur = head;
    while (cur != null) {
        if (cur.val == val) {
            cur = cur.next;
            continue;
        }

        Node next = cur.next;

        cur.next = null;
        if (result == null) {
            result = cur;
        } else {
            last.next = cur;
        }

        last = cur;

        cur = next;
    }

    return result;
}

}

public class MyLinkedList {
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);//pos
head.next.next.next = new Node(4);

Node pos = head.next.next;
    pushAfter(pos, 100);//在pos之后入100

    // 1, 2, 3, 100, 4
}

private static void pushAfter(Node pos, int val) {
    Node node = new Node(val);

    node.next = pos.next;
    pos.next = node;
}

private static void popAfter(Node pos) {
    pos.next = pos.next.next;
}

}

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


新闻名称:关于链表:删除指定元素、在指定位置后插入或删除元素-创新互联
网站网址:http://www.wjwzjz.com/article/ddsjjs.html
在线咨询
服务热线
服务热线:028-86922220
TOP