链表数据定义
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; } }
Leetcode 203 力扣
解法一:原链表区分头节点删除和非头结点删除
public static ListNode removeElements(ListNode head, int val) { if (head == null){ return head; } // 头节点删除 while (head != null && head.val == val) { head = head.next; } // 非头结点删除 ListNode cur = head; while (cur.next != null){ if (cur.next.val == val){ cur.next = cur.next.next; }else { cur = cur.next; } } return head; }
解法二:使用虚拟头结点,虚拟头节点next指向head头节点联系起来
public ListNode removeElements虚拟头结点(ListNode head, int val) { if (head == null){ return head; } ListNode dummy = new ListNode(-1,head); // 虚拟头节点下next是原链表的头节点 dummy.next = head; ListNode cur = dummy; while (cur.next != null){ if (cur.next.val == val){ cur.next = cur.next.next; }else { cur = cur.next; } } // 原链表的头节点是虚拟头结点的next指向 head = dummy.next; return head; }
Leetcode 206 力扣
解法一:双指针
public ListNode reverseList(ListNode head) { // 画图理解 if (head == null){ return head; } ListNode pre = null; ListNode cur = head; ListNode temp =null; while (cur != null){ temp = cur.next; // 先保存下一个节点 cur.next = pre; // 反转 // 虚拟头节点和cur整体后移一位 pre = cur; cur = temp; } return pre; }
解法二:双指针基础上递归(优先熟悉双指针)
public ListNode reverseList递归(ListNode head) { return reverse(null,head); } public ListNode reverse(ListNode pre,ListNode cur) { if (cur == null){ return pre; } ListNode temp =null; temp = cur.next; // 先保存下一个节点 cur.next = pre; // 反转 return reverse(cur,temp); // 赋值取决于双指针解法pre和cur定义 }
Leetcode 707 力扣
学习视频后做出来,还需要再理解深刻一些,画图确定n位置一定是cur.next节点才能操作
题目链接/文章讲解/视频讲解:
代码随想录
解法代码
class MyLinkedList { //size存储链表元素的个数 int size; //虚拟头结点 ListNode head; //初始化链表 public MyLinkedList() { size = 0; head = new ListNode(0); } public int get(int index) { if (index < 0 || index > size){ return -1; } ListNode cur = head; for (int i = 0; i <= index; i++) { cur = cur.next; } return cur.val; } public void addAtHead(int val) { addAtIndex(0,val); } public void addAtTail(int val) { addAtIndex(size,val); } public void addAtIndex(int index, int val) { if (index >size){ return; } if (index <0){ index =0; } size++; ListNode pre = head; for (int i = 0; i <= index; i++) { pre = pre.next; } ListNode newNode = new ListNode(val); newNode.next = pre.next; pre.next = newNode; } public void deleteAtIndex(int index) { if (index < 0 || index >size){ return; } size--; if (index ==0){ head = head.next; return; } ListNode pred = head; for (int i = 0; i < index ; i++) { pred = pred.next; } pred.next = pred.next.next; } }