This repository acts as a personal archive for my solutions to EdX course *Data Structures and Software Design* from PennX.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.0 KiB

  1. import java.util.LinkedList;
  2. import java.util.ArrayList;
  3. /*
  4. * SD2x Homework #1
  5. * Implement the methods below according to the specification in the assignment description.
  6. * Please be sure not to change the signature of any of the methods!
  7. */
  8. public class LinkedListUtils {
  9. public static void insertSorted(LinkedList<Integer> list, int value) {
  10. if( list == null ) { return; } // Terminate if the list is null
  11. if(list.size() == 0){
  12. list.add(value);
  13. return;
  14. }
  15. int pointer = 0;
  16. for(int i : list){
  17. if( i > value ){
  18. break;
  19. }
  20. pointer++;
  21. }
  22. if(pointer == list.size()){
  23. list.addLast(value);
  24. }else{
  25. list.add(pointer, value);
  26. }
  27. }
  28. public static int calcMinimum(ArrayList<String> list){ // Return the index of the minimum element on the Array
  29. int i, j ;
  30. for(i = 0; i < list.size(); i++){
  31. for(j = 0; j < list.size(); j++){
  32. if(j == i){
  33. continue;
  34. }
  35. if(list.get(i).compareTo(list.get(j)) > 0){
  36. break;
  37. }
  38. }
  39. if( j == list.size()){
  40. return i;
  41. }
  42. }
  43. return -1;
  44. }
  45. public static void removeMaximumValues(LinkedList<String> list, int N) {
  46. if( list == null ){ return; }
  47. if( N < 1 ) { return; }
  48. if( list.size() <= N ){ list.clear(); return; }
  49. ArrayList<String> maxElements = new ArrayList<String>(N);
  50. for(int i = 0; i < N; i++){
  51. maxElements.add(list.get(i));
  52. }
  53. int maxVal, diff;
  54. String str;
  55. for(int i = N; i < list.size(); i++){
  56. maxVal = 0;
  57. str = list.get(i);
  58. for(int j = 0; j < N; j++){
  59. diff = str.compareTo(maxElements.get(j));
  60. if(diff == 0){ // Break if string collision is detected
  61. maxVal = 0;
  62. break;
  63. }
  64. maxVal = diff > maxVal ? diff : maxVal;
  65. }
  66. if(maxVal > 0){
  67. maxElements.set(calcMinimum(maxElements), str);
  68. }
  69. }
  70. list.removeAll(maxElements); // Remove all occurences of the elements in array from LL
  71. }
  72. public static boolean containsSubsequence(LinkedList<Integer> one, LinkedList<Integer> two) {
  73. if( one == null || two == null ){ return false; }
  74. if( one.size() < two.size() || one.size() == 0 || two.size() == 0){ return false; }
  75. int j;
  76. for(int i = 0; i <= one.size() - two.size(); i++){
  77. if(one.get(i) != two.getFirst()){
  78. continue;
  79. }
  80. for(j = 1; j < two.size(); j++){
  81. if(one.get(i + j) != two.get(j)){
  82. break;
  83. }
  84. }
  85. if(j == two.size()){
  86. return true;
  87. }
  88. }
  89. return false;
  90. }
  91. }