关于链表:删除指定元素、在指定位置后插入或删除元素

发布时间:2020-08-03 22:25:04 作者:凉白开dream
来源:网络 阅读:357

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

一,删除链表中与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;
}

}

推荐阅读:
  1. LeetCode如何删除链表中指定的所有元素
  2. JS如何在数组指定位置插入元素

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 链表 指定元素 除元素

上一篇:倒数的用法_shell脚本

下一篇:从vmware workstation9.0中 上载虚拟服务器到ESXI

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》