说明:思路中写的是伪代码,为了表达意思。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; }
}