LeetCode 707. 设计链表

707. 设计链表

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。

  • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。

  • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。

  • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。

  • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/design-linked-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


  • 1.虚拟头节点

思路:
1.通过维护一个虚拟的头节点dummyHead来操作链表,从而实现添加和删除操作。

public class MyLinkedList {

    private class Node {
        public int val;
        public Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }

        public Node(int val) {
            this(val, null);
        }

        public Node() {
            this(0, null);
        }
    }

    //使用虚拟头节点
    private Node dummyHead;
    private int size;

    /**
     * Initialize your data structure here.
     */
    public MyLinkedList() {
        dummyHead = new Node();
        size = 0;
    }

    /**
     * Get the value of the index-th node in the linked list. If the index is invalid, return -1.
     */
    public int get(int index) {
        if (index < 0 || index >= size) return -1;
        Node cur = dummyHead.next;   //头节点
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    /**
     * judge linked list is empty?
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
     */
    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    /**
     * Append a node of value val to the last element of the linked list.
     */
    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    /**
     * Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
     */
    public void addAtIndex(int index, int val) {
        if (index < 0 || index > size) {
            return;
        }
        Node prev = dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        prev.next = new Node(val, prev.next);
        size++;
    }

    /**
     * Delete the index-th node in the linked list, if the index is valid.
     */
    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) throw new IllegalArgumentException("Add filed, index is illegal");
        Node prev = dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        Node retNode = prev.next;
        prev.next = retNode.next;
        retNode.next = null;     //loitering object != memory leak
        size--;
    }
}
  • 2.常规解法

思路:
通过维护当前节点cur完成相关操作

public class MyLinkedList2 {

    private class Node {

        private int val;
        private Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }

        public Node(int val) {
            this(val, null);
        }

        public Node() {
            this(0, null);
        }
    }

    private Node head;
    private int size;

    public MyLinkedList2() {
        head = null;
        size = 0;
    }

    public void addAtHead(int val) {
//        Node node = new Node(val);
//        node.next = head;
//        head = node;
        head = new Node(val, head);
        size ++;
    }

    public void addAtIndex(int index, int val) {
        if (index < 0 || index > size) {
            return;
        }
        if (index == 0) {
            addAtHead(val);
        } else {
            Node prev = head;
            for (int i = 0; i < index - 1; i++) {
                prev = prev.next;
            }
            prev.next = new Node(val, prev.next);
            size ++;
        }

    }

    public void deleteAtHead() {
        head = head.next;
        size--;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        if (index == 0) {
            deleteAtHead();
        } else {
            Node prev = head;
            for (int i = 0; i < index - 1; i++) {
                prev = prev.next;
            }
            Node cur = prev.next;
            prev.next = cur.next;
            cur.next = null;
            size--;
        }
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        if (index == 0) {
            return head.val;
        } else {
            Node cur = head.next;
            for (int i = 0; i < index - 1; i++) {
                cur = cur.next;
            }
            return cur.val;
        }
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        Node cur = head;
        while (cur != null) {
            res.append(cur.val + "->");
            cur = cur.next;
        }
        res.append("NULL");
        return res.toString();
    }
 }   
  • 测试用例

public static void main(String[] args) {
        MyLinkedList2 myLinkedList2 = new MyLinkedList2();
        myLinkedList2.addAtHead(1);
        System.out.println(myLinkedList2);
        myLinkedList2.addAtTail(3);
        System.out.println(myLinkedList2);
        myLinkedList2.addAtIndex(1, 2);
        System.out.println(myLinkedList2);
        myLinkedList2.deleteAtIndex(1);
        System.out.println(myLinkedList2);
        myLinkedList2.get(1);
        System.out.println(myLinkedList2);
    }
  • 结果

不知道测试用例是否有问题,一直无法通过leetcode中最后一个用例。

  • 源码

  • 我会随时更新新的算法,并尽可能尝试不同解法,如果发现问题请指正
  • Github
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天已经是7号,是007作业雨时间,可我的文章还没个头绪,因为知道自己有些懈怠了,所以硬着头皮做了小组长。全靠是参...
    心曙_d605阅读 3,355评论 2 6