我正在尝试实现LinkedList,我遇到的问题是在此列表中添加元素,我已经在主类中添加了元素,并且想知道如何在列表的开头添加元素,并且在列表的末尾。当前可以打印,但是当我添加新元素时无法看到它们。我还想知道有关获取链表大小的信息。
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
int size;
public void AddBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
this.size++;
head = newNode;
}
public void addAtEnd(int data) {
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
public void getSize() {
System.out.println(size);
}
public void printList(Node head) {
Node current = head;
while (current !=null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
Node head = new Node(25);
Node second = new Node(22);
Node third = new Node(7);
head.next = second;
second.next = third;
ll.AddBeginning(20);
ll.printList(head);
}
}
我想在开头添加20,在结尾添加另一个整数。
答案 0 :(得分:0)
您正在将节点20 this.rankingObs = this.rankingService.getAll().pipe(
mergeMap(ranking => {
// an array of all observables which will return the merged rank and member data
const ranksWithMembers = ranking.map(rank=>{
return this.memberService.get(rank.key).pipe(
map(member=>{
return {
...rank,
firstName: member.firstName,
lastName: member.lastName,
keyName: member.key,
}
})
)
})
// does not emit until all observables in array emit. Emits all results.
return forkJoin(ranksWithMembers)
}),
).subscribe(...)
添加到ll.AddBeginning(20);
,并尝试使用LinkedList.head
打印列表
解决方案: 第1步:要么初始化LinkedList.head,要么
Tester.head (declared in main method)
第2步:无需将head变量传递给printList()函数。它打印出LinkedList.head元素
- Using constructor or
LinkedList ll = new LinkedList(head);
public LinkedList(Node head) {
this.head = head;
}
- Assign head to LinkedList object i.e., ll
ll.head = head; // Need to initialize Linked List with Head
代码:
测试器主要方法
ll.printList(); //Here you passing Tester.head not required
LinkedList.PrintList方法
ll.head = head; // Need to initialize Linked List with Head
ll.AddBeginning(20); //Here actually adding node to linkedList head
ll.printList(); //Here you passing Tester.head not required