本文共 2474 字,大约阅读时间需要 8 分钟。
package util;import java.util.NoSuchElementException;/** * @Author lyr * @create 2020/6/28 13:13 */public class LinkedList { static class Node { private int value; private Node next; public Node(int value) { this.value = value; } } private Node first; private Node last; /** * addFirst * addLast * deleteFirst * deleteLast * contains * indexOf */ public void addLast(int item) { Node n = new Node(item); if (isEmpty()) { first = last = n; } else { last.next = n; last = n; } } public void addFirst(int item) { Node node = new Node(item); if (isEmpty()) { first = last = node; } else { node.next = first; first = node; } } public int indexOf(int item) { int index = 0; Node current = first; while (current != null) { if (current.value == item) return index; index++; current = current.next; } return -1; } public boolean contains(int item) { return indexOf(item) != -1; } public void removeFirst() { if (isEmpty()) { throw new NoSuchElementException(); } if (first == last) { first = last = null; } // [10,20,30] //first ->20 Node second = first.next; //移除连接 first.next = null; first = second; } /** * remove the last element */ public void removeLast() { if (isEmpty()) { throw new NoSuchElementException(); } if (first == last) { first = last = null; return; } Node previous = getPrevious(last); last = previous; last.next = null; } private Node getPrevious(Node node) { Node current = first; while (current != null) { if (current.next == node) return current; current = current.next; } return null; } private boolean isEmpty() { return this.first == null; }}
后续补充
public int getKthFromTheEnd(int k) { if(isEmpty()) throw new IllegalStateException(); var a = first; var b = a; for(var i = 0;i"); it = it.next; } return sb.append("null").toString(); }
转载地址:http://vhuzi.baihongyu.com/