【leetcode】第2章 链表

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--;
    }
}

反转链表

  1. 双指针法
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;
}
  1. 迭代法
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);
}

你可能感兴趣的:(刷题,leetcode,链表,java)