网站建设案例收费情况,个人信息展示页面设计,平面素材设计网站,电影宣传推广方案203. 移除链表元素
方法#xff1a;添加一个虚拟节点#xff0c;这不用考虑头节点删除情况
public ListNode removeElements(ListNode head, int val) {// 虚拟节点#xff0c;指向头节点ListNode dummy new ListNode(0);dummy.next head;ListNode p dummy;// 找到被删…203. 移除链表元素
方法添加一个虚拟节点这不用考虑头节点删除情况
public ListNode removeElements(ListNode head, int val) {// 虚拟节点指向头节点ListNode dummy new ListNode(0);dummy.next head;ListNode p dummy;// 找到被删除节点的前一个节点进行删除while (p.next ! null) {// 若相等则移除元素if (p.next.val val) {p.next p.next.next;}else {p p.next;}}return dummy.next;
}707. 设计链表
带有
class ListNode{int val;ListNode next;ListNode(){};ListNode(int val) {this.val val;}
}class MyLinkedList {int size;ListNode dummy;// 初始化链表public MyLinkedList() {size 0;dummy new ListNode(0);}public int get(int index) {if (index 0 || index size) {return -1;}ListNode cur dummy;for (int i index; i 0; --i){cur cur.next;}return cur.next.val;}public void addAtHead(int val) {ListNode node new ListNode(val);node.next dummy.next;dummy.next node;size;}public void addAtTail(int val) {// 找到最后一个元素ListNode cur dummy;ListNode node new ListNode(val);while (cur.next ! null) {cur cur.next;}cur.next node;size;}public void addAtIndex(int index, int val) {if (index size) return;// 找到第index个节点之前ListNode cur dummy;ListNode node new ListNode(val);for (int i index; i 0; --i){cur cur.next;}node.next cur.next;cur.next node;size;}public void deleteAtIndex(int index) {if (index 0 || index size) return;ListNode cur dummy;if (index 0) {dummy dummy.next;}for (int i index; i 0; --i){cur cur.next;}cur.next cur.next.next;size--;}
}
反转链表
双指针法
public static ListNode reverseList(ListNode head) {// 输入head [1,2,3,4,5]//输出[5,4,3,2,1]ListNode pre null;ListNode cur head;while (cur ! null) {ListNode tmp cur.next;// 反转cur.next pre;// 迭代当前指向pre cur;cur tmp;}return pre;
}迭代法
public static ListNode reverseList(ListNode head) {// 输入head [1,2,3,4,5]//输出[5,4,3,2,1]return reverse(null,head);
}public static ListNode reverse(ListNode pre,ListNode cur){if (cur null) {return pre;}ListNode tmp cur.next;cur.next pre;return reverse(cur,tmp);
}