所以我在Java中有一个单链列表
public class ListNode {
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
现在我要尝试做的是在列表中填充String number = "213214"
,它实际上只是一个数字。现在,每个节点都将是该数字中的一位数字。
这是我目前所拥有的。
int firstnode = Integer.parseInt(String.valueOf(m.charAt(0)));
ListNode root = new ListNode(firstnode);
for(int i = 1; i<m.length(); ++i) {
while (root.next == null) {
root.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
}
root = root.next;
}
所以我正在努力做到这一点
root(2)->node(1)->node(3)->node(2)->node(1)->node(4)->ListEND
有什么想法吗?
据我检查,您的代码运行正常。只是您在更改用于插入新ListNode
的根变量时丢失了根节点(头)。为此使用临时变量。以下是更改后的代码。
public static void main(String[] args) {
String m = "213214";
int firstnode = Integer.parseInt(String.valueOf(m.charAt(0)));
ListNode root = new ListNode(firstnode);
ListNode temp = root;
for (int i = 1; i < m.length(); ++i) {
while (temp.next == null) {
temp.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
}
temp = temp.next;
}
temp = root;
while (temp != null) {
System.out.print("->" + temp.val);
temp=temp.next;
}
}
而且您也不需要for循环中的while循环。它总是只运行一次。
尝试这种方式
public class SingleLinkedList {
LinkedList root = null;
public static void main(String[] args) {
SingleLinkedList sll = new SingleLinkedList();
sll.root = new LinkedList(1);
sll.root.next = new LinkedList(2);
sll.root.next.next = new LinkedList(3);
sll.root.next.next.next = new LinkedList(4);
sll.root.next.next.next.next = new LinkedList(5);
while (sll.root != null){
System.out.println("sll.root.value = " + sll.root.value);
sll.root = sll.root.next;
}
}
}
class LinkedList{
int value;
LinkedList next;
LinkedList(int data){
value = data;
next = null;
}
}
我认为这应该对您有用。由于root已分配给新的root元素,因此无法打印。保留根元素引用并将其用于打印逻辑
ListNode root = new ListNode(firstnode);
ListNode printRoot = root;
for (int i = 1; i < m.length(); i++) {
if (root.next == null) {
root.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
root = root.next;
}
}
while(printRoot !=null) {
System.out.println(printRoot.val);
printRoot = printRoot.next;
}
由于存在根节点。以下代码有效。
import java.util.*;
import java.util.stream.*;
public class ListNode {
public static void main(final String... args) {
final ListNode root = new ListNode(0);
"213214".chars()
.map(Character::getNumericValue)
.mapToObj(ListNode::new)
.reduce(root, (n1, n2) -> {
n1.next = n2;
return n2;
});
;
System.out.println(root);
}
ListNode(final int value) {
super();
this.value = value;
}
@Override
public String toString() {
return super.toString() + "{"
+ "value=" + value
+ ",next=" + next
+ "}";
}
private int value;
private ListNode next;
}