提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣203. 移除链表元素
- 二、力扣707. 设计链表
- 三、力扣
前言
递归法相对抽象一些,但是其实和双指针法是一样的逻辑,同样是当cur为空的时候循环结束,不断将cur指向pre的过程
一、力扣203. 移除链表元素
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode removeElements(ListNode head, int val) {ListNode node = new ListNode(-1);node.next = head;ListNode p = node;while(p.next != null){if(p.next.val == val){p.next = p.next.next;}else{p = p.next;}}return node.next;}
}
二、力扣707. 设计链表
class MyLinkedList {int count;DLink head, tail;public MyLinkedList() {this.count = 0;head = new DLink();tail = new DLink();head.next = tail;tail.prev = head;}public int get(int index) {if (index < 0 || index >= count) {return -1;}DLink p = head;for (int i = 0; i <= index; i++) {p = p.next;}return p.val;}public void addAtHead(int val) {addAtIndex(0,val);}public void addAtTail(int val) {addAtIndex(count,val);}public void addAtIndex(int index, int val) {if (index < 0 || index > count) {return;}DLink p = new DLink();p.val = val;DLink r = head;for (int i = 0; i < index; i++) {r = r.next;}p.next = r.next;r.next.prev = p;p.prev = r;r.next = p;count++;}public void deleteAtIndex(int index) {if (index < 0 || index >= count) {return;}DLink p = head;for (int i = 0; i < index; i++) {p = p.next;}p.next = p.next.next;count--;}
}class DLink {int val;DLink next, prev;public DLink() {}
}/*** Your MyLinkedList object will be instantiated and called as such:* MyLinkedList obj = new MyLinkedList();* int param_1 = obj.get(index);* obj.addAtHead(val);* obj.addAtTail(val);* obj.addAtIndex(index,val);* obj.deleteAtIndex(index);*/