Compare commits

..

No commits in common. "bd860423c48005e435b49d9c38497f35bbe29fda" and "042fbd164aa1ff995831c7a718c57f4fa574b3df" have entirely different histories.

2 changed files with 4 additions and 56 deletions

View File

@ -1,52 +1,12 @@
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 implements Iterable<Integer> { public class SinglyLinkedList {
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;
@ -56,14 +16,12 @@ public class SinglyLinkedList implements Iterable<Integer> {
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) {

View File

@ -12,14 +12,4 @@ public class SinglyLinkedListTest {
list.addFirst(6); list.addFirst(6);
list.loop0(i -> System.out.println(i + " ")); list.loop0(i -> System.out.println(i + " "));
} }
@Test
public void singlyLinkedListIteratorTest(){
list.addFirst(1);
list.addFirst(3);
list.addFirst(5);
list.addFirst(6);
for (Integer value: list) {
System.out.println(value);
}
}
} }