链表结构

  1. public class ListNode {
  2. int val;
  3. ListNode next;
  4. public ListNode() {
  5. }
  6. public ListNode(int val) {
  7. this.val = val;
  8. }
  9. public ListNode(int val, ListNode next) {
  10. this.val = val;
  11. this.next = next;
  12. }
  13. }

添加虚拟头节点

看到删除的题目,考虑虚拟头节点
添加虚拟节点后,删除操作可以统一

  1. public ListNode removeElements(ListNode head, int val) {
  2. if (head == null) return null;
  3. ListNode dummy = new ListNode(-1, head);
  4. ListNode pre = dummy;
  5. ListNode cur = head;
  6. while (cur != null) {
  7. if (cur.val == val) {
  8. pre.next = cur.next;
  9. }
  10. //不相等,则移动pre指针
  11. else {
  12. pre = cur;
  13. }
  14. cur = cur.next;
  15. }
  16. return dummy.next;
  17. }public ListNode removeElements(ListNode head, int val) {
  18. if
  19. }

设计链表

707. 设计链表

反转链表

双指针

  1. public ListNode reverseList(ListNode head) {
  2. ListNode cur = head;
  3. ListNode pre = null;
  4. while (cur != null) {
  5. ListNode tmp = cur;
  6. cur = cur.next;
  7. tmp.next = pre;
  8. pre = tmp;
  9. }
  10. return pre;
  11. }