关于链表:删除指定元素、在指定位置后插入或删除元素
说明:思路中写的是伪代码,为了表达意思。
一,删除链表中与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;}
}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。