關於鏈表:刪除指定元素、在指定位置後插入或刪除元素

說明:思路中寫的是僞代碼,爲了表達意思。node

一,刪除鏈表中與val相等的結點ide

須要兩個結點 cur和prev(做爲cur的前驅結點)
遍歷整個鏈表,與給定的val做比較,
若是相等:prev.next=cur.next;
若是不相等:cur=cur.next;this

2、在指定POS後插入、刪除結點
插入:pos.next=node;
node.next=pos.next;
刪除:pos.next=pos.next.nextcode

代碼以下:orm

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

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

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

}it

class Solution {
public Node removeElements(Node head, int val) {
Node result = null;
Node last = null; // 記錄目前 result 中的最後一個結點io

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;
}

}ast

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);form

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;
}

}

相關文章
相關標籤/搜索