Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class Question2
- {
- public static void main(String[] args)
- {
- Scanner input = new Scanner(System.in);
- Cell<Integer> list1,list2;
- int n,m1,m2;
- System.out.print("Enter a list (of integers): ");
- String line = input.nextLine();
- list1 = parseIntLinkedList(line);
- System.out.print("Enter a number: ");
- n = input.nextInt();
- System.out.println("Before: " + linkedListToString(list1));
- removeDest(n, list1);
- System.out.println("After: " + linkedListToString(list1));
- }
- private static <T> void removeDest(T item, Cell<T> list) {
- removeDest(item, list, null);
- }
- private static <T> void removeDest(T item, Cell<T> current, Cell<T> prev) {
- if (null == current) {
- return;
- }
- else if (item.equals(current.first)) {
- if (null != prev) {
- prev.next = current.next;
- }
- else if (null != current.next){
- current.first = current.next.first;
- current.next = current.next.next;
- }
- else {
- current.first = null;
- }
- }
- else {
- removeDest(item, current.next, current);
- }
- }
- ////////////////////////////////////////////////////////////
- private static Cell<Integer> parseIntLinkedList(String str)
- {
- Cell<Integer> list=null;
- String line = str.trim();
- String contents = line.substring(1,line.length()-1).trim();
- if(contents.length()==0)
- return null;
- String[] nums = contents.split(",");
- for(int i=nums.length-1; i>=0; i--)
- {
- String num = nums[i].trim();
- list = new Cell<Integer>(new Integer(num),list);
- }
- return list;
- }
- private static <T> String linkedListToString(Cell<T> list)
- {
- String str="[";
- if(list!=null)
- {
- str+=list.first;
- for(Cell<T> ptr=list.next; ptr!=null; ptr=ptr.next)
- str+=","+ptr.first;
- }
- return str+"]";
- }
- private static class Cell <T>
- {
- T first;
- Cell<T> next;
- Cell(T f,Cell<T> n)
- {
- first=f;
- next=n;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement