我被這個所謂的非常簡單的資料結構問題困住了。問題的鏈接在這里:https ://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem?isFullScreen=true
有人可以指出如何正確處理這個問題嗎?
import java.io.*;
import java.util.*;
public class Solution {
private class Node{
int data;
Node next;
private Node (int data){
this.data = data;
this.next = null;
}
}
static void setHead(LinkedList<Integer> lList){
Node head;
if (lList.peek() != null){
head = lList.peek();
return;
}else{
return;
}
}
static void input(LinkedList<Integer> lList){
Scanner scanner = new Scanner(System.in);
int count = scanner.nextInt();
int i = 0;
while (i < count){
int data = scanner.nextInt();
lList.add(data);
i ;
}
scanner.close();
return;
}
static void printLinkedList(LinkedList<Integer> lList){
while(lList.head != null){
Sdtout.println(lList.head.data);
this.head = head.next;
}
return;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
LinkedList<Integer> n1 = new LinkedList<Integer>();
setHead(n1);
input(n1);
printLinkedList(n1);
}
}
錯誤:(我很困惑如何設定頭節點給出鏈表)
Solution.java:19: error: incompatible types: Integer cannot be converted to Solution.Node
head = lList.peek();
^
Solution.java:39: error: cannot find symbol
while(lList.head != null){
^
symbol: variable head
location: variable lList of type LinkedList<Integer>
Solution.java:40: error: cannot find symbol
Sdtout.println(lList.head.data);
^
symbol: variable head
location: variable lList of type LinkedList<Integer>
Solution.java:40: error: cannot find symbol
Sdtout.println(lList.head.data);
^
symbol: variable Sdtout
location: class Solution
Solution.java:41: error: non-static variable this cannot be referenced from a static context
this.head = head.next;
^
Solution.java:41: error: cannot find symbol
this.head = head.next;
^
symbol: variable head
Solution.java:41: error: cannot find symbol
this.head = head.next;
^
symbol: variable head
location: class Solution
7 errors
uj5u.com熱心網友回復:
您不需要使用LinkedListJDK 中內置的類。相反,您必須使用單鏈表資料結構的非常基本的自定義實作。
如果您選擇語言級別Java 8,那么將為您提供幾乎準備就緒的實作。
您只需要實作一個方法,該方法可以根據挑戰描述精確執行所需的操作,僅此而已:
public static void printLinkedList(SinglyLinkedListNode head) {
SinglyLinkedListNode cur = head;
while (cur != null) { // while current node exists
System.out.println(cur.data); // print its data
cur = cur.next; // and reassign the current node to its next node
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/489537.html
