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<k-1;++i) {
b = b.next;
if(b==null)
throw new IllegalStateException();
}
while(b!=last) {
a = a.next;
b = b.next;
}
return a.value;
}
public void reverse() {
reverse0();
var temp = first;
first = last;
last = temp;
}
private Node reverse0() {
Node pre=null,current=first,next = null;
while(current!=null) {
next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}
@Override
public String toString() {
Node it = first;
StringBuilder sb = new StringBuilder();
while (it!=null) {
sb.append(it.value).append("-> ");
it = it.next;
}
return sb.append("null").toString();
}