Java Generic Linked List Problem:
How do I remove a slice of a linked list and add its data to another linked list in java?
Example:
Private<T> head;
Private int size;
Public List<T> slice(int from, int to) {
// This method will remove the data from the given range (inclusive) and add it to a new List and return this new list.
}
Program:
//class GenericLinkedList
import java.util.LinkedList;
import java.util.List;
public class GenericLinkedList {
public static void main(String[] args) {
//create variable for
LinkedList
List<String> list = new
LinkedList<String>();
//add element to
linkedlist
list.add("Slice");
list.add("Linked");
list.add("LinkedList");
list.add("Remove");
list.add("Add");
//print original list
System.out.println("Original List :
" + list);
//create an object of Generics
with list parameter
Generics generics = new
Generics(list);
//print the sliced list from the
given list by calling slice() method
System.out.println("Sliced List : "
+ generics.slice(1, 4));
//print the modified original
list after slice operation
System.out.println("Modified List
after slice : " + generics.getList());
}
}
//class Generics
import java.util.LinkedList;
import java.util.List;
//<T> is added to class to indicate class will support
generics
public class Generics<T> {
// variable to store generic list
private List<T> list;
// list parameterized constructor
public Generics(List<T> list) {
this.list = list;// initialize
list
}
// definition of slice() method
public <T> List<T> slice(int from, int to)
{
// create new linkedlist to
store the slice list content
List<T> sliceList = new
LinkedList<T>();
// iterate list over (from,
to)
for (int i = from; i < to; i++)
{
// add element
to slicelist
sliceList.add((T) this.list.get(i));
}
// iterate list to remove sliced
elements
for (int i = to - 1; i > from -
1; i--) {
this.list.remove(i);
}
return sliceList;//slicelist
contains elements with given range(inclusive) not exclusive
}
// getter method for list variable
public List<T> getList() {
return list;
}
// setter method for list variable
public void setList(List<T> list) {
this.list = list;
}
}
Sample output of the program:
Original List : [Slice, Linked, LinkedList, Remove, Add]
Sliced List : [Linked, LinkedList, Remove]
Modified List after slice : [Slice, Add]
Get Answers For Free
Most questions answered within 1 hours.