Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class Question2
  4. {
  5.  
  6.  public static void main(String[] args)
  7.  {
  8.   Scanner input = new Scanner(System.in);
  9.   Cell<Integer> list1,list2;
  10.   int n,m1,m2;
  11.   System.out.print("Enter a list (of integers): ");
  12.   String line = input.nextLine();
  13.   list1 = parseIntLinkedList(line);
  14.   System.out.print("Enter a number: ");
  15.   n = input.nextInt();
  16.  
  17.   System.out.println("Before: " + linkedListToString(list1));
  18.   removeDest(n, list1);
  19.   System.out.println("After:  " + linkedListToString(list1));
  20.  }
  21.  
  22.  private static <T> void removeDest(T item, Cell<T> list) {
  23.    removeDest(item, list, null);
  24.  }
  25.  
  26.  private static <T> void removeDest(T item, Cell<T> current, Cell<T> prev) {
  27.    if (null == current) {
  28.      return;
  29.    }
  30.    else if (item.equals(current.first)) {
  31.      if (null != prev) {
  32.        prev.next = current.next;
  33.      }
  34.      else if (null != current.next){
  35.        current.first = current.next.first;
  36.        current.next = current.next.next;
  37.      }
  38.      else {
  39.        current.first = null;
  40.      }
  41.    }
  42.    else {
  43.      removeDest(item, current.next, current);
  44.    }
  45.  }
  46.  
  47.  ////////////////////////////////////////////////////////////
  48.  
  49.  private static Cell<Integer> parseIntLinkedList(String str)
  50.  {
  51.   Cell<Integer> list=null;
  52.   String line = str.trim();
  53.   String contents = line.substring(1,line.length()-1).trim();
  54.   if(contents.length()==0)
  55.      return null;
  56.   String[] nums = contents.split(",");
  57.   for(int i=nums.length-1; i>=0; i--)
  58.       {
  59.        String num = nums[i].trim();
  60.        list = new Cell<Integer>(new Integer(num),list);
  61.       }
  62.   return list;
  63.  }
  64.  
  65.  private static <T> String linkedListToString(Cell<T> list)
  66.  {
  67.   String str="[";
  68.   if(list!=null)
  69.      {
  70.       str+=list.first;
  71.       for(Cell<T> ptr=list.next; ptr!=null; ptr=ptr.next)
  72.          str+=","+ptr.first;
  73.      }
  74.   return str+"]";
  75.  }
  76.  
  77.  private static class Cell <T>
  78.  {
  79.   T first;
  80.   Cell<T> next;
  81.  
  82.   Cell(T f,Cell<T> n)
  83.   {
  84.    first=f;
  85.    next=n;
  86.   }
  87.  }
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement