Java Signature Test
Xem dạng PDFMy Linked List
Implement a class named MyLinkedList that represents a mutable list of integers.
You only need to implement the required class, constructor, and methods. Do not read input and do not print output. The grading system will provide a hidden wrapper that creates your object and calls your methods.
Required class
public class MyLinkedList {
public MyLinkedList();
public void addFirst(int value);
public void addLast(int value);
public int get(int index);
public int remove(int index);
public int size();
}
Method requirements
MyLinkedList()
Creates an empty list.
void addFirst(int value)
Adds value to the beginning of the list.
Example:
Current list: [10, 20]
addFirst(5)
Result: [5, 10, 20]
void addLast(int value)
Adds value to the end of the list.
Example:
Current list: [10, 20]
addLast(30)
Result: [10, 20, 30]
int get(int index)
Returns the value at the given 0-based index.
If index < 0 or index >= size(), return -1.
Example:
List: [5, 10, 20]
get(0) -> 5
get(2) -> 20
get(3) -> -1
get(-1) -> -1
int remove(int index)
Removes the element at the given 0-based index and returns the removed value.
If the index is invalid, do not modify the list and return -1.
Example:
List: [5, 10, 20]
remove(1) -> 10
List becomes:
[5, 20]
int size()
Returns the current number of elements in the list.
Requirements
- The list is initially empty.
- Indices are 0-based.
- The object must preserve its state across multiple method calls.
- Invalid
getandremoveoperations must return-1. - Submit only the
MyLinkedListclass. - Do not implement input parsing or output printing.
- A
main()method is not required.
Example behavior
Suppose the grading system performs:
Create a new MyLinkedList
addLast(10)
addLast(20)
addFirst(5)
size()
get(0)
get(1)
get(2)
remove(1)
size()
The returned values are:
3
5
10
20
10
2
The final list is:
[5, 20]
Submission template
public class MyLinkedList {
public MyLinkedList() {
// your code
}
public void addFirst(int value) {
// your code
}
public void addLast(int value) {
// your code
}
public int get(int index) {
// your code
return -1;
}
public int remove(int index) {
// your code
return -1;
}
public int size() {
// your code
return 0;
}
}
Bình luận