Compare commits

..

2 Commits

Author SHA1 Message Date
wangsiyuan bd860423c4 Update SinglyLinkedListTest.java 2024-07-11 17:23:00 +08:00
wangsiyuan dfda3d7f08 Update SinglyLinkedList.java 2024-07-11 17:22:58 +08:00
2 changed files with 56 additions and 4 deletions

View File

@ -1,12 +1,52 @@
package com.nbee.solution.practice;
import java.util.Iterator;
import java.util.function.Consumer;
/**
*
*/
public class SinglyLinkedList {
public class SinglyLinkedList implements Iterable<Integer> {
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 {
int value;
Node next;
@ -16,12 +56,14 @@ public class SinglyLinkedList {
this.next = next;
}
}
public void addFirst(int value) {
//链表为空
// head = new Node(value,null);
//链表非空,包含了链表为空的情况
head = new Node(value, head);
}
public void loop(Consumer<Integer> consumer) {
Node p = head;
while (p != null) {

View File

@ -12,4 +12,14 @@ public class SinglyLinkedListTest {
list.addFirst(6);
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);
}
}
}