Update SinglyLinkedList.java
parent
042fbd164a
commit
dfda3d7f08
|
|
@ -1,12 +1,52 @@
|
||||||
package com.nbee.solution.practice;
|
package com.nbee.solution.practice;
|
||||||
|
|
||||||
|
import java.util.Iterator;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 链表类
|
* 链表类
|
||||||
*/
|
*/
|
||||||
public class SinglyLinkedList {
|
public class SinglyLinkedList implements Iterable<Integer> {
|
||||||
private Node head;
|
private Node head;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Iterator<Integer> iterator() {
|
||||||
|
return new Iterator<Integer>() {
|
||||||
|
Node p = head;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean hasNext() {
|
||||||
|
return p != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer next() {
|
||||||
|
int value = p.value;
|
||||||
|
p = p.next;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node findLast() {
|
||||||
|
if (head == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Node p;
|
||||||
|
for (p = head; p != null; p = p.next) {
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addLast(int value) {
|
||||||
|
Node last = findLast();
|
||||||
|
if (last == null){
|
||||||
|
addFirst(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
last.next = new Node(value, null);
|
||||||
|
}
|
||||||
|
|
||||||
private static class Node {
|
private static class Node {
|
||||||
int value;
|
int value;
|
||||||
Node next;
|
Node next;
|
||||||
|
|
@ -16,12 +56,14 @@ public class SinglyLinkedList {
|
||||||
this.next = next;
|
this.next = next;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addFirst(int value) {
|
public void addFirst(int value) {
|
||||||
//链表为空
|
//链表为空
|
||||||
// head = new Node(value,null);
|
// head = new Node(value,null);
|
||||||
//链表非空,包含了链表为空的情况
|
//链表非空,包含了链表为空的情况
|
||||||
head = new Node(value,head);
|
head = new Node(value, head);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loop(Consumer<Integer> consumer) {
|
public void loop(Consumer<Integer> consumer) {
|
||||||
Node p = head;
|
Node p = head;
|
||||||
while (p != null) {
|
while (p != null) {
|
||||||
|
|
@ -30,7 +72,7 @@ public class SinglyLinkedList {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loop0 (Consumer<Integer> consumer){
|
public void loop0(Consumer<Integer> consumer) {
|
||||||
for (Node p = head; p != null; p = p.next) {
|
for (Node p = head; p != null; p = p.next) {
|
||||||
consumer.accept(p.value);
|
consumer.accept(p.value);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue