复习CS61B project1之前的题目

lab 1 考点:

substring/concat/equals/equalsIgnoreCase/indexOf

all index from 0 not 1.

完整代码:

package lab1;

/* Names.java */

import java.io.*;

/** The Names class provides a single function, main, that will
 *   perform various manipulations of the name John Fitzgerald Kennedy. 
 *   This is a modification of the program on page 43 of Arnow and Weiss.
 */

class Names {

/** Performs various string operations on the name John Fitzgerald Kennedy.
 *  @param arg is not used.
 */
  public static void main(String arg[]) {
    String first = "John";
    String middle = "Fitzgerald";
    String last = "Kennedy";
    String initials;
    String firstInit, middleInit, lastInit;

    firstInit = first.substring(0,1);
    middleInit = middle.substring(0,1);
    lastInit = last.substring(0,1);
    initials = firstInit.concat(middleInit);
    initials = initials.concat(lastInit);

    System.out.println();
    System.out.println(first + " " + middle + " " + last + " ");
    System.out.println(initials);
    System.out.println(last + ", " + first + " " + middle);
    System.out.println(last + ", " + first + " " + middleInit +".");
    System.out.println(first.toUpperCase() + " " + last.toUpperCase());

    System.out.println(first + " equals john is " + first.equals("john"));
    System.out.println(first + " equals john (ignoring case) is " 
               + first.equalsIgnoreCase("john"));
    System.out.println("The character at index 3 in " + middle + " is " +
               middle.substring(3,4));
    System.out.println("The index of "gerald" within " + middle + " is " +
               middle.indexOf("gerald"));
    System.out.println("The index of "gerald" within " + last + " is " +
               last.indexOf("gerald"));

    System.out.println();
  }
}
View Code

 sortoutnames.java

package sortoutname;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class SortOutNames {
    
     public static void readTxtFile(String filePath){
         List<String> Namelist = new ArrayList<String>();
         int i=0,j;
            try {
                    String encoding="GBK";
                    File file=new File(filePath);
                    if(file.isFile() && file.exists()){ //判断文件是否存在
                        InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考虑到编码格式
                        BufferedReader bufferedReader = new BufferedReader(read);
                        String lineTxt = null;
                        while((lineTxt = bufferedReader.readLine()) != null){
                            
                            Namelist.add(lineTxt+"
");
                            i=i+1;
                        }
                        System.out.println(Namelist);
                        Collections.sort(Namelist);
                        System.out.println(Namelist);
                        read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
            } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            }
            try {
                  File  file=new File("AfterOrder.txt");
                   FileWriter fw=new FileWriter(file);
                   for (j=0;j<i;j++){
                   fw.write(Namelist.get(j));                  
                   }
                   fw.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
         
        }
    public static void main(String arg[]) {
        String filePath = "roster.txt";
//      "res/";
        readTxtFile(filePath);
        
    }
    
}
View Code

homework 1 考点:

opencommerical是老师上课讲过的例子,现学现卖/怎样读取网页检查元素/readline()会自动向下一个进行读取 

 1 class OpenCommerical {
 2 
 3   /** Prompts the user for the name X of a company (a single string), opens
 4    *  the Web site corresponding to www.X.com, and prints the first five lines
 5    *  of the Web page in reverse order.
 6    *  @param arg is not used.
 7    *  @exception Exception thrown if there are any problems parsing the 
 8    *             user's input or opening the connection.
 9    */
10   public static void main(String[] arg) throws Exception {
11 
12     BufferedReader keyboard;
13     String inputLine;
14 
15     keyboard = new BufferedReader(new InputStreamReader(System.in));
16 
17     System.out.print("Please enter the name of a company (without spaces): ");
18     System.out.flush();        /* Make sure the line is printed immediately. */
19     inputLine = keyboard.readLine();
20 
21     /* Replace this comment with your solution.  */
22     URL u = new URL("http://www."+inputLine+".com/");
23     InputStream ins = u.openStream();
24     InputStreamReader isr = new InputStreamReader(ins);
25     String[] FiveLines = new String[5];
26     BufferedReader Baidu = new BufferedReader(isr);
27     for(int i=0; i<5 ;i++){       
28         FiveLines[i] = Baidu.readLine();        
29     }
30     for(int j=4;j>=0;j--){
31     System.out.println(FiveLines[j]);
32     }
33    }
34 }
View Code

nuke2 

import java.io.*;

public class Programe2 {
public static String change(String s){
char[]c=s.toCharArray();
String s1="";
s1+=c[0];
for(int i=2;i<c.length;i++)
s1+=c[i];
return s1;
}
public static void main(String[]args) throws IOException{
BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your words: ");
System.out.flush();
String s=keyboard.readLine();
String output=change(s);
System.out.print(output);

}

}

 或者用substring直接做

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class Nuke2 {
    public static void main(String[] arg) throws Exception {

        BufferedReader keyboard;
        String inputLine;
        String MovedWord;
        keyboard = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Please enter a word: ");
        System.out.flush();        /* Make sure the line is printed immediately. */
        inputLine = keyboard.readLine();
        /* Replace this comment with your solution.  */
        MovedWord = inputLine.substring(0, 1)+inputLine.substring(2, inputLine.length());
        System.out.print("REMOVE SECOND CHARACTER:"+ MovedWord);
       }

}
View Code

lab2 考点

gcd辗转相除

  static private int gcd (int x, int y) {  //辗转相除法
    /* Replace the following line with your solution. */
      if(y==0)
          return x;
      else 
          return gcd(y,x%y);
  }

构造函数

System.out.println("..." + d1);//这里d1会自动调用toString(); 可以不用写出来。

  1 class Fraction {
  2 
  3   /* private fields within a Fraction. */
  4   static private int numberOfFractions = 0;
  5 
  6   private int numerator;
  7   private int denominator;
  8 
  9   /** Constructs a Fraction n/d. 
 10    *  @param n is the numerator.  Must be nonnegative.
 11    *  @param d is the denominator.  Must be positive.
 12    */
 13   public Fraction(int n, int d) {
 14     if (n < 0) {
 15       System.out.println("Fatal error:  Negative numerator.");
 16       System.exit(0);
 17     }
 18     if (d < 1) {
 19       System.out.println("Fatal error:  Non-positive denominator.");
 20       System.exit(0);
 21     }
 22     numberOfFractions++;
 23     numerator = n; 
 24     denominator = d;
 25   }
 26 
 27   /** Constructs a Fraction n/1. 
 28    *  @param n is the numerator.  Must be nonnegative.
 29    */
 30   public Fraction(int n) {
 31     this(n, 1);    //call the two-parameters constructor 
 32   }
 33 
 34   /** Constructs a Fraction 0/1. 
 35    */
 36   public Fraction() {
 37     this(0,1);   // call the two-parameters constructor
 38   }
 39 
 40   /** Copies the Fraction "original".
 41    */
 42   public Fraction(Fraction original) {
 43     this(original.numerator,original.denominator);
 44   }
 45 
 46   /** Converts this Fraction to a string format:  "numerator/denominator."
 47    *  Fractions should be printed in reduced form (part of your assignment is
 48    *  to make this true).
 49    *  @return a String representation of this Fraction.
 50    */
 51   public String toString() {
 52     int thisGcd = gcd(numerator, denominator);
 53 
 54     return (numerator / thisGcd + "/" + denominator / thisGcd);
 55   }
 56 
 57   /** Return the sum of two fractions.
 58    *  @param f2 is the Fraction to be added.
 59    *  @return the result of adding f2 to this Fraction.
 60    */
 61   public Fraction add(Fraction f2) {
 62     Fraction r = new Fraction((numerator * f2.denominator) +
 63                   (f2.numerator * denominator),
 64                   denominator * f2.denominator);
 65     return r;
 66   }
 67 
 68   /** Replaces this Fraction's numerator with a new value.
 69    *  @param numerator is the new numerator.  Must be nonnegative.
 70    */
 71   public void changeNumerator(int numerator) { // DO NOT CHANGE THIS SIGNATURE!
 72     // Fix the bug that prevents this method from working correctly.
 73     if (numerator < 0) {
 74       System.out.println("Fatal error:  Negative numerator.");
 75       System.exit(0);
 76     }
 77     this.numerator = numerator;
 78 
 79   }
 80 
 81   /** Returns the number of Fraction objects in existence.
 82    *  @return the number of Fraction objects in existence.
 83    */
 84   public int fracs() {                         // DO NOT CHANGE THIS SIGNATURE!
 85     // Fix the bug that prevents this method from working correctly.
 86     return numberOfFractions;
 87   }
 88 
 89   /** Computes the greatest common divisor (gcd) of the two inputs.
 90    * @param x must be nonnegative
 91    * @param y must be nonnegative
 92    * @return the gcd of x and y
 93    */
 94   static private int gcd (int x, int y) {  //辗转相除法
 95     /* Replace the following line with your solution. */
 96       if(y==0)
 97           return x;
 98       else 
 99           return gcd(y,x%y);
100   }
101 
102   /** Put the Fraction class through some tests.
103    * @param argv is not used.
104    */
105   public static void main(String[] argv) {
106 
107     /* Test all four contructors and toString. */
108     Fraction f0 = new Fraction(0,1);
109     Fraction f1 = new Fraction(3);
110     Fraction f2 = new Fraction(12, 20);
111     Fraction f3 = new Fraction(f2);
112 
113     System.out.println("
Testing constructors and toString():");
114     System.out.println("The fraction f0 is " + f0.toString());
115     System.out.println("The fraction f1 is " + f1);    // toString is implicit.
116     System.out.println("The fraction f2 is " + f2);
117     System.out.println("The fraction f3 is " + f3 + ", which should equal f2");
118 
119     /* Test the add method. */
120     System.out.println("
Testing add:");
121     
122 
123     
124     Fraction sumOfTwo = f1.add(f2);              // Sum of f1 and f2.
125     Fraction sumOfThree = f0.add(f1).add(f2);             // Sum of f0, f1, and f2.
126 
127     System.out.println("The sum of " + f1 + " and " + f2 + " is " + sumOfTwo);
128     System.out.println("The sum of " + f0 + ", " + f1 + " and " + f2 + " is " +
129                        sumOfThree);
130     
131 
132     /* Test the methods used in Part III. */
133     System.out.println("
Testing changeNumerator and fracs:");
134 
135     f3.changeNumerator(7);
136     System.out.println("Now f3 is " + f3 + ", which should be 7/20");
137     System.out.println("The total number of Fraction objects is " +
138                        f3.fracs());
139 
140     /* Test gcd function (static method). */
141     System.out.println("
Testing gcd:");
142     System.out.println("The gcd of 2 and 10 is: " + gcd(2, 10));
143     System.out.println("The gcd of 15 and 5 is: " + gcd(15, 5));
144     System.out.println("The gcd of 24 and 18 is: " + gcd(24, 18));
145     System.out.println("The gcd of 10 and 10 is: " + gcd(10, 10));
146     System.out.println("The gcd of 21 and 400 is: " + gcd(21, 400));
147   }
148 }
View Code

homework2考点

闰年判断 

  public static boolean isLeapYear(int year) {
      if((year%4==0&&year%100!=0)||(year%400==0)){
          return true;   
          }else return false;                     // replace this line with your solution
  }

正则表达+split分割字符串+Integer.parseInt()方法将String转化为int

  public Date(String s) {
      if(s.matches("\d{1,2}\/\d{1,2}\/\d{1,4}")){
          String[] d=s.split("/");
          month=Integer.parseInt(d[0]);
          day=Integer.parseInt(d[1]);
          year=Integer.parseInt(d[2]);
      }else System.exit(0);
  }

string int 相互转换知识补充

http://blog.csdn.net/memray/article/details/7312817/  转自MemRay博客

String ==》int

1). int i = Integer.parseInt([String]); 或

i = Integer.parseInt([String],[int radix]);

2). int i = Integer.valueOf(my_str).intValue();

int ==》String 

1.) String s = String.valueOf(i);

2.) String s = Integer.toString(i);

3.) String s = "" + i;

注: Double, Float, Long 转成字串的方法大同小异.

 完整代码:

package hw2;

/* Date.java */

import java.io.*;

class Date {

  /* Put your private data fields here. */
    private int month;
    private int day;
    private int year;

  /** Constructs a date with the given month, day and year.   If the date is
   *  not valid, the entire program will halt with an error message.
   *  @param month is a month, numbered in the range 1...12.
   *  @param day is between 1 and the number of days in the given month.
   *  @param year is the year in question, with no digits omitted.
   */
  public Date(int month, int day, int year) {
      if(isValidDate(month,day,year)){
          this.month=month;
          this.day=day;
          this.year=year;
      }else System.exit(0); 
  }

  /** Constructs a Date object corresponding to the given string.
   *  @param s should be a string of the form "month/day/year" where month must
   *  be one or two digits, day must be one or two digits, and year must be
   *  between 1 and 4 digits.  If s does not match these requirements or is not
   *  a valid date, the program halts with an error message.
   */
  public Date(String s) {
      if(s.matches("\d{1,2}\/\d{1,2}\/\d{1,4}")){
          String[] d=s.split("/");
          month=Integer.parseInt(d[0]);
          day=Integer.parseInt(d[1]);
          year=Integer.parseInt(d[2]);
      }else System.exit(0);
  }

  /** Checks whether the given year is a leap year.
   *  @return true if and only if the input year is a leap year.
   */
  public static boolean isLeapYear(int year) {
      if((year%4==0&&year%100!=0)||(year%400==0)){
          return true;   
          }else return false;                     // replace this line with your solution
  }

  /** Returns the number of days in a given month.
   *  @param month is a month, numbered in the range 1...12.
   *  @param year is the year in question, with no digits omitted.
   *  @return the number of days in the given month.
   */
  public static int daysInMonth(int month, int year) {      
          if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
          return 31;
          }else if(month==2){
              if(isLeapYear(year)){
              return 29;
              }else return 28;
          }else return 30;                                                   // replace this line with your solution
  }

  /** Checks whether the given date is valid.
   *  @return true if and only if month/day/year constitute a valid date.
   *
   *  Years prior to A.D. 1 are NOT valid.
   */
  public static boolean isValidDate(int month, int day, int year) {
      if(year>=1&&day<=daysInMonth(month,year)&&month>=1&&month<=12){
          
          return true;
          
      }else return false;                        // replace this line with your solution
  }

  /** Returns a string representation of this date in the form month/day/year.
   *  The month, day, and year are printed in full as integers; for example,
   *  12/7/2006 or 3/21/407.
   *  @return a String representation of this date.
   */
  public String toString() {
      
    return month+"/"+day+"/"+year;                     // replace this line with your solution
  }

  /** Determines whether this Date is before the Date d.
   *  @return true if and only if this Date is before d. 
   */
  public boolean isBefore(Date d) {
      if(this.year < d.year){
          return true;         
      }else if (this.year==d.year){
          if(this.month<d.month){
              return true;
          }else if(this.month==d.month){
              if(this.day<d.day){
                  return true;
              }else return false;
          }else return false;
      }else return false;                           // replace this line with your solution
  }

  /** Determines whether this Date is after the Date d.
   *  @return true if and only if this Date is after d. 
   */
  public boolean isAfter(Date d) {
    if(!isBefore(d)&&(d!=this)){
        return true;
    }else return false;                        // replace this line with your solution
  }

  /** Returns the number of this Date in the year.
   *  @return a number n in the range 1...366, inclusive, such that this Date
   *  is the nth day of its year.  (366 is only used for December 31 in a leap
   *  year.)
   */
  public int dayInYear(int month, int year, int day) {
      int m = month;
      int sum1 = 0;
      switch(--m){      //注意是--m 因为如果是9.04号 9月不能一整个月都算进去
      case 12: sum1+=31;
      case 11: sum1+=30;
      case 10: sum1+=31;
      case 9: sum1+=30;
      case 8: sum1+=31;
      case 7: sum1+=31;
      case 6: sum1+=30;
      case 5: sum1+=31;
      case 4: sum1+=30;
      case 3: sum1+=31;
      case 2: 
      if(isLeapYear(year)) 
      sum1+=29;
      else
      sum1+=28;
      case 1: sum1+=31;
      break;    //这里加上一个break语句
      default:
      break; 
      }
    sum1 = sum1 + day;
    return sum1;                           // replace this line with your solution
  }
  
/*  public int dayInYear() {
      int total=0;
    for(int i=1;i<month;i++)
        total+=daysInMonth(i,this.year);
    total+=this.day;
    return total;
  }*/

  /** Determines the difference in days between d and this Date.  For example,
   *  if this Date is 12/15/1997 and d is 12/14/1997, the difference is 1.
   *  If this Date occurs before d, the result is negative.
   *  @return the difference in days between d and this date.
   */
  public int difference(Date d) {
    return dayInAll(year, month, day)-dayInAll(d.year,d.month,d.day);                           // replace this line with your solution
  }
  public int dayInAll(int year,int month,int day){
      int sum = 0;
      for(int n = year-1;n >= 1; n--){
          if(isLeapYear(n)){
              sum = sum +366;
          }else{sum = sum + 365;}
      }
      sum = sum + dayInYear(month, year,day);
      return sum;
  }

  public static void main(String[] argv) {
    System.out.println("
Testing constructors.");
    Date d1 = new Date(1, 1, 1);
    System.out.println("Date should be 1/1/1: " + d1); //这里会自动调用toString();
    d1 = new Date("2/4/2");
    System.out.println("Date should be 2/4/2: " + d1);
    d1 = new Date("2/29/2000");
    System.out.println("Date should be 2/29/2000: " + d1);
    d1 = new Date("2/29/1904");
    System.out.println("Date should be 2/29/1904: " + d1);

    d1 = new Date(12, 31, 1975);
    System.out.println("Date should be 12/31/1975: " + d1);
    Date d2 = new Date("1/1/1976");
    System.out.println("Date should be 1/1/1976: " + d2);
    Date d3 = new Date("1/2/1976");
    System.out.println("Date should be 1/2/1976: " + d3);

    Date d4 = new Date("2/27/1977");
    Date d5 = new Date("8/31/2110");

    /* I recommend you write code to test the isLeapYear function! */

    System.out.println("
Testing before and after.");
    System.out.println(d2 + " after " + d1 + " should be true: " + 
                       d2.isAfter(d1));
    System.out.println(d3 + " after " + d2 + " should be true: " + 
                       d3.isAfter(d2));
    System.out.println(d1 + " after " + d1 + " should be false: " + 
                       d1.isAfter(d1));
    System.out.println(d1 + " after " + d2 + " should be false: " + 
                       d1.isAfter(d2));
    System.out.println(d2 + " after " + d3 + " should be false: " + 
                       d2.isAfter(d3));

    System.out.println(d1 + " before " + d2 + " should be true: " + 
                       d1.isBefore(d2));
    System.out.println(d2 + " before " + d3 + " should be true: " + 
                       d2.isBefore(d3));
    System.out.println(d1 + " before " + d1 + " should be false: " + 
                       d1.isBefore(d1));
    System.out.println(d2 + " before " + d1 + " should be false: " + 
                       d2.isBefore(d1));
    System.out.println(d3 + " before " + d2 + " should be false: " + 
                       d3.isBefore(d2));

    System.out.println("
Testing difference.");
    System.out.println(d1 + " - " + d1  + " should be 0: " + 
                       d1.difference(d1));
    System.out.println(d2 + " - " + d1  + " should be 1: " + 
                       d2.difference(d1));
    System.out.println(d3 + " - " + d1  + " should be 2: " + 
                       d3.difference(d1));
    System.out.println(d3 + " - " + d4  + " should be -422: " + 
                       d3.difference(d4));
    System.out.println(d5 + " - " + d4  + " should be 48762: " + 
                       d5.difference(d4));
  }
}
View Code

Lab3

完整代码:

SListNode.java

package lab3;

/* SListNode.java */

/**
 *  SListNode is a class used internally by the SList class.  An SList object
 *  is a singly-linked list, and an SListNode is a node of a singly-linked
 *  list.  Each SListNode has two references:  one to an object, and one to
 *  the next node in the list.
 *
 *  @author Kathy Yelick and Jonathan Shewchuk
 */

class SListNode {
  Object item;
  SListNode next;

  /**
   *  SListNode() (with one parameter) constructs a list node referencing the
   *  item "obj".
   */

  SListNode(Object obj) {
    item = obj;
    next = null;
  }

  /**
   *  SListNode() (with two parameters) constructs a list node referencing the
   *  item "obj", whose next list node is to be "next".
   */

  SListNode(Object obj, SListNode next) {
    item = obj;
    this.next = next;
  }

}
View Code

SList.java

package lab3;

/* SList.java */

/**
 *  The SList class is a singly-linked implementation of the linked list
 *  abstraction.  SLists are mutable data structures, which can grow at either
 *  end.
 *
 *  @author Kathy Yelick and Jonathan Shewchuk
 **/

public class SList {

  private SListNode head;
  private int size;
  private SListNode tail;

  /**
   *  SList() constructs an empty list.
   **/

  public SList() {
    size = 0;
    head = null;
    tail = null;
  }

  /**
   *  isEmpty() indicates whether the list is empty.
   *  @return true if the list is empty, false otherwise.
   **/

  public boolean isEmpty() {
    return size == 0;
  }

  /**
   *  length() returns the length of this list.
   *  @return the length of this list.
   **/

  public int length() {
    return size;
  }

  /**
   *  insertFront() inserts item "obj" at the beginning of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertFront(Object obj) {
    head = new SListNode(obj, head);
    if(tail==null){
        tail=head;
    }
    
    size++;
  }

  /**
   *  insertEnd() inserts item "obj" at the end of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertEnd(Object obj) {
    if (tail==null) {
      tail = new SListNode(obj);
      head = tail;
    } else {
 //     SListNode node = head;
 //     while (node.next != null) {
 //       node = node.next;
 //     }
 //     node.next = new SListNode(obj);       
        tail.next = new SListNode(obj);
        tail = tail.next;
    }
    size++;
  }
/* others' codes */
//  public void insertEnd(Object obj) {
//      if (tail==null){
//        insertFront(obj);
//      } else {
//        tail.next = new SListNode(obj, null);
//        tail = tail.next;
//        size++;
//      }
//    }
  /**
   *  nth() returns the item at the specified position.  If position < 1 or
   *  position > this.length(), null is returned.  Otherwise, the item at
   *  position "position" is returned.  The list does not change.
   *  @param position the desired position, from 1 to length(), in the list.
   *  @return the item at the given position in the list.
   **/

  public Object nth(int position) {
    SListNode currentNode;

    if ((position < 1) || (head == null)) {
      return null;
    } else {
      currentNode = head;
      while (position > 1) {
        currentNode = currentNode.next;
        if (currentNode == null) {
          return null;
        }
        position--;
      }
      return currentNode.item;
    }
  } 

  /**
   *  toString() converts the list to a String.
   *  @return a String representation of the list.
   **/

  public String toString() {
    int i;
    Object obj;
    String result = "[  ";

    SListNode cur = head;

    while (cur != null) {
      obj = cur.item;
      result = result + obj.toString() + "  ";
      cur = cur.next;
    }
    result = result + "]";
    return result;
  }


  /**
   *  main() runs test cases on the SList class.  Prints summary
   *  information on basic operations and halts with an error (and a stack
   *  trace) if any of the tests fail.
   **/

  public static void main (String[] args) {
    // Fill in your solution for Part I here.
     SList n1= new SList();
     n1.insertEnd(6);
     n1.insertEnd(9);
     n1.insertEnd(12);
     System.out.println("Here is a list after insertEnd(6 9 12) on an empty list: "
               + n1.toString());
     n1.insertEnd(15);
     n1.insertFront(3);
     System.out.println("Here is a list after insertEnd(15) and insertFront(3) on previous list: "
               + n1.toString());
    testEmpty();
    testAfterInsertFront();
    testAfterInsertEnd();
  }

    
  /**
   *  testEmpty() tests toString(), isEmpty(), length(), insertFront(), and
   *  insertEnd() on an empty list.  Prints summary information of the tests
   *  and halts the program if errors are detected.
   **/

  private static void testEmpty() {
    SList lst1 = new SList();
    SList lst2 = new SList();
    System.out.println();
    System.out.println("Here is a list after construction: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  ]"),
              "toString on newly constructed list failed");

    System.out.println("isEmpty() should be true. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == true,
              "isEmpty() on newly constructed list failed");    

    System.out.println("length() should be 0. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 0, 
              "length on newly constructed list failed");    
    lst1.insertFront(new Integer(3));
    System.out.println("Here is a list after insertFront(3) to an empty list: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  3  ]"),
              "InsertFront on empty list failed");
    lst2.insertEnd(new Integer(5));
    System.out.println("Here is a list after insertEnd(5) on an empty list: "
               + lst2.toString());
    TestHelper.verify(lst2.toString().equals("[  5  ]"),
              "insertEnd on empty list failed");
  }

  /**
   *  testAfterInsertFront() tests toString(), isEmpty(), length(),
   *  insertFront(), and insertEnd() after insertFront().  Prints summary
   *  information of the tests and halts the program if errors are detected.
   **/

  private static void testAfterInsertFront() {
    SList lst1 = new SList();
    lst1.insertFront(new Integer(3));
    lst1.insertFront(new Integer(2));
    lst1.insertFront(new Integer(1));
    System.out.println();
    System.out.println("Here is a list after insertFront 3, 2, 1: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  1  2  3  ]"),
              "InsertFronts on non-empty list failed");
    System.out.println("isEmpty() should be false. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == false,
              "isEmpty() after insertFront failed");    
    System.out.println("length() should be 3. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 3, 
              "length() after insertFront failed");
    lst1.insertEnd(new Integer(4));
    System.out.println("Here is the same list after insertEnd(4): "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  1  2  3  4  ]"),
              "insertEnd on non-empty list failed");
  }
    
  /**
   *  testAfterInsertEnd() tests toString(), isEmpty(), length(),
   *  insertFront(), and insertEnd() after insertEnd().  Prints summary
   *  information of the tests and halts the program if errors are detected.
   **/

  private static void testAfterInsertEnd() {
    SList lst1 = new SList();
    lst1.insertEnd(new Integer(6));
    lst1.insertEnd(new Integer(7));
    System.out.println();
    System.out.println("Here is a list after insertEnd 6, 7: "
               + lst1.toString());
    System.out.println("isEmpty() should be false. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == false,
              "isEmpty() after insertEnd failed");    
    System.out.println("length() should be 2. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 2, 
              "length() after insertEndfailed");
    lst1.insertFront(new Integer(5));
    System.out.println("Here is the same list after insertFront(5): "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  5  6  7  ]"),
              "insertFront after insertEnd failed");
  }
}
View Code

Homework3

完整代码:

homework3.java

package hw3;

/* SList.java */

/**
 *  The SList class is a singly-linked implementation of the linked list
 *  abstraction.  SLists are mutable data structures, which can grow at either
 *  end.
 *
 *  @author Kathy Yelick and Jonathan Shewchuk
 **/

public class SList {

  private SListNode head;
  private int size;

  /**
   *  SList() constructs an empty list.
   **/

  public SList() {
    size = 0;
    head = null;
  }

  /**
   *  isEmpty() indicates whether the list is empty.
   *  @return true if the list is empty, false otherwise.
   **/

  public boolean isEmpty() {
    return size == 0;
  }

  /**
   *  length() returns the length of this list.
   *  @return the length of this list.
   **/

  public int length() {
    return size;
  }

  /**
   *  insertFront() inserts item "obj" at the beginning of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertFront(Object obj) {
    head = new SListNode(obj, head);
    size++;
  }

  /**
   *  insertEnd() inserts item "obj" at the end of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertEnd(Object obj) {
    if (head == null) {
      head = new SListNode(obj);
    } else {
      SListNode node = head;
      while (node.next != null) {
        node = node.next;
      }
      node.next = new SListNode(obj);
    }
    size++;
  }

  /**
   *  nth() returns the item at the specified position.  If position < 1 or
   *  position > this.length(), null is returned.  Otherwise, the item at
   *  position "position" is returned.  The list does not change.
   *  @param position the desired position, from 1 to length(), in the list.
   *  @return the item at the given position in the list.
   **/

  public Object nth(int position) {
    SListNode currentNode;

    if ((position < 1) || (head == null)) {
      return null;
    } else {
      currentNode = head;
      while (position > 1) {
        currentNode = currentNode.next;
        if (currentNode == null) {
          return null;
        }
        position--;
      }
      return currentNode.item;
    }
  }

  /**
   *  squish() takes this list and, wherever two or more consecutive items are
   *  equal(), it removes duplicate nodes so that only one consecutive copy
   *  remains.  Hence, no two consecutive items in this list are equal() upon
   *  completion of the procedure.
   *
   *  After squish() executes, the list may well be shorter than when squish()
   *  began.  No extra items are added to make up for those removed.
   *
   *  For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the
   *  output list is [ 0 1 0 3 1 0 ].
   *
   *  IMPORTANT:  Be sure you use the equals() method, and not the "=="
   *  operator, to compare items.
   **/

  public void squish() {
    // Fill in your solution here.  (Ours is eleven lines long.)
      SListNode CurrentNode ,PreNode;            
      if(head!=null){     
         PreNode = this.head;
         CurrentNode = PreNode.next;
      while(CurrentNode!=null){
          if(PreNode.item.equals(CurrentNode.item)){
              PreNode.next=CurrentNode.next;
              CurrentNode=PreNode.next;
          }else{
              PreNode=PreNode.next;
              CurrentNode=PreNode.next;
              }
          }
      }
      
  }

  /**
   *  twin() takes this list and doubles its length by replacing each node
   *  with two consecutive nodes referencing the same item.
   *
   *  For example, if the input list is [ 3 7 4 2 2 ], the
   *  output list is [ 3 3 7 7 4 4 2 2 2 2 ].
   *
   *  IMPORTANT:  Do not try to make new copies of the items themselves.
   *  Just copy the references to the items.
   **/

/*  public void twin() {   //完全可以不用NextNode 可以用.next.next
    // Fill in your solution here.  (Ours is seven lines long.)
      if(head!=null){
          SListNode CurrentNode = this.head;
          SListNode NextNode = CurrentNode.next;
          while(CurrentNode!=null){
              CurrentNode.next=new SListNode(CurrentNode.item,CurrentNode.next);
              CurrentNode=NextNode;
              if(NextNode==null)
                      {break;}else{
              NextNode = NextNode.next;}
              }
          }
  }*/

  public void twin() {   //完全可以不用NextNode 可以用.next.next
        // Fill in your solution here.  (Ours is seven lines long.)
          if(head!=null){
              SListNode CurrentNode = this.head;
//              SListNode NextNode = CurrentNode.next;
              while(CurrentNode!=null){
                  CurrentNode.next=new SListNode(CurrentNode.item,CurrentNode.next);
                  if(CurrentNode.next==null){
                      break;
                      }else{
                 CurrentNode=CurrentNode.next.next;}
                  }
              }
      }
  /**
   *  toString() converts the list to a String.
   *  @return a String representation of the list.
   **/

  public String toString() {
    int i;
    Object obj;
    String result = "[  ";

    SListNode cur = head;

    while (cur != null) {
      obj = cur.item;
      result = result + obj.toString() + "  ";
      cur = cur.next;
    }
    result = result + "]";
    return result;
  }


  /**
   *  main() runs test cases on the SList class.  Prints summary
   *  information on basic operations and halts with an error (and a stack
   *  trace) if any of the tests fail.
   **/

  public static void main (String[] args) {
    testEmpty();
    testAfterInsertFront();
    testAfterInsertEnd();
  }

    
  /**
   *  testEmpty() tests toString(), isEmpty(), length(), insertFront(), and
   *  insertEnd() on an empty list.  Prints summary information of the tests
   *  and halts the program if errors are detected.
   **/

  private static void testEmpty() {
    SList lst1 = new SList();
    SList lst2 = new SList();
    System.out.println();
    System.out.println("Here is a list after construction: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  ]"),
              "toString on newly constructed list failed");

    System.out.println("isEmpty() should be true. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == true,
              "isEmpty() on newly constructed list failed");    

    System.out.println("length() should be 0. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 0, 
              "length on newly constructed list failed");    
    lst1.insertFront(new Integer(3));
    System.out.println("Here is a list after insertFront(3) to an empty list: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  3  ]"),
              "InsertFront on empty list failed");
    lst2.insertEnd(new Integer(5));
    System.out.println("Here is a list after insertEnd(5) on an empty list: "
               + lst2.toString());
    TestHelper.verify(lst2.toString().equals("[  5  ]"),
              "insertEnd on empty list failed");
  }

  /**
   *  testAfterInsertFront() tests toString(), isEmpty(), length(),
   *  insertFront(), and insertEnd() after insertFront().  Prints summary
   *  information of the tests and halts the program if errors are detected.
   **/

  private static void testAfterInsertFront() {
    SList lst1 = new SList();
    lst1.insertFront(new Integer(3));
    lst1.insertFront(new Integer(2));
    lst1.insertFront(new Integer(1));
    System.out.println();
    System.out.println("Here is a list after insertFront 3, 2, 1: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  1  2  3  ]"),
              "InsertFronts on non-empty list failed");
    System.out.println("isEmpty() should be false. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == false,
              "isEmpty() after insertFront failed");    
    System.out.println("length() should be 3. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 3, 
              "length() after insertFront failed");
    lst1.insertEnd(new Integer(4));
    System.out.println("Here is the same list after insertEnd(4): "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  1  2  3  4  ]"),
              "insertEnd on non-empty list failed");
  }
    
  /**
   *  testAfterInsertEnd() tests toString(), isEmpty(), length(),
   *  insertFront(), and insertEnd() after insertEnd().  Prints summary
   *  information of the tests and halts the program if errors are detected.
   **/

  private static void testAfterInsertEnd() {
    SList lst1 = new SList();
    lst1.insertEnd(new Integer(6));
    lst1.insertEnd(new Integer(7));
    System.out.println();
    System.out.println("Here is a list after insertEnd 6, 7: "
               + lst1.toString());
    System.out.println("isEmpty() should be false. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == false,
              "isEmpty() after insertEnd failed");    
    System.out.println("length() should be 2. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 2, 
              "length() after insertEndfailed");
    lst1.insertFront(new Integer(5));
    System.out.println("Here is the same list after insertFront(5): "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  5  6  7  ]"),
              "insertFront after insertEnd failed");
  }
}
View Code

SList.java

package hw3;

/* SList.java */

/**
 *  The SList class is a singly-linked implementation of the linked list
 *  abstraction.  SLists are mutable data structures, which can grow at either
 *  end.
 *
 *  @author Kathy Yelick and Jonathan Shewchuk
 **/

public class SList {

  private SListNode head;
  private int size;

  /**
   *  SList() constructs an empty list.
   **/

  public SList() {
    size = 0;
    head = null;
  }

  /**
   *  isEmpty() indicates whether the list is empty.
   *  @return true if the list is empty, false otherwise.
   **/

  public boolean isEmpty() {
    return size == 0;
  }

  /**
   *  length() returns the length of this list.
   *  @return the length of this list.
   **/

  public int length() {
    return size;
  }

  /**
   *  insertFront() inserts item "obj" at the beginning of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertFront(Object obj) {
    head = new SListNode(obj, head);
    size++;
  }

  /**
   *  insertEnd() inserts item "obj" at the end of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertEnd(Object obj) {
    if (head == null) {
      head = new SListNode(obj);
    } else {
      SListNode node = head;
      while (node.next != null) {
        node = node.next;
      }
      node.next = new SListNode(obj);
    }
    size++;
  }

  /**
   *  nth() returns the item at the specified position.  If position < 1 or
   *  position > this.length(), null is returned.  Otherwise, the item at
   *  position "position" is returned.  The list does not change.
   *  @param position the desired position, from 1 to length(), in the list.
   *  @return the item at the given position in the list.
   **/

  public Object nth(int position) {
    SListNode currentNode;

    if ((position < 1) || (head == null)) {
      return null;
    } else {
      currentNode = head;
      while (position > 1) {
        currentNode = currentNode.next;
        if (currentNode == null) {
          return null;
        }
        position--;
      }
      return currentNode.item;
    }
  }

  /**
   *  squish() takes this list and, wherever two or more consecutive items are
   *  equal(), it removes duplicate nodes so that only one consecutive copy
   *  remains.  Hence, no two consecutive items in this list are equal() upon
   *  completion of the procedure.
   *
   *  After squish() executes, the list may well be shorter than when squish()
   *  began.  No extra items are added to make up for those removed.
   *
   *  For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the
   *  output list is [ 0 1 0 3 1 0 ].
   *
   *  IMPORTANT:  Be sure you use the equals() method, and not the "=="
   *  operator, to compare items.
   **/

  public void squish() {
    // Fill in your solution here.  (Ours is eleven lines long.)
      SListNode CurrentNode ,PreNode;            
      if(head!=null){     
         PreNode = this.head;
         CurrentNode = PreNode.next;
      while(CurrentNode!=null){
          if(PreNode.item.equals(CurrentNode.item)){
              PreNode.next=CurrentNode.next;
              CurrentNode=PreNode.next;
          }else{
              PreNode=PreNode.next;
              CurrentNode=PreNode.next;
              }
          }
      }
      
  }

  /**
   *  twin() takes this list and doubles its length by replacing each node
   *  with two consecutive nodes referencing the same item.
   *
   *  For example, if the input list is [ 3 7 4 2 2 ], the
   *  output list is [ 3 3 7 7 4 4 2 2 2 2 ].
   *
   *  IMPORTANT:  Do not try to make new copies of the items themselves.
   *  Just copy the references to the items.
   **/

/*  public void twin() {   //完全可以不用NextNode 可以用.next.next
    // Fill in your solution here.  (Ours is seven lines long.)
      if(head!=null){
          SListNode CurrentNode = this.head;
          SListNode NextNode = CurrentNode.next;
          while(CurrentNode!=null){
              CurrentNode.next=new SListNode(CurrentNode.item,CurrentNode.next);
              CurrentNode=NextNode;
              if(NextNode==null)
                      {break;}else{
              NextNode = NextNode.next;}
              }
          }
  }*/

  public void twin() {   //完全可以不用NextNode 可以用.next.next
        // Fill in your solution here.  (Ours is seven lines long.)
          if(head!=null){
              SListNode CurrentNode = this.head;
//              SListNode NextNode = CurrentNode.next;
              while(CurrentNode!=null){
                  CurrentNode.next=new SListNode(CurrentNode.item,CurrentNode.next);
                  if(CurrentNode.next==null){
                      break;
                      }else{
                 CurrentNode=CurrentNode.next.next;}
                  }
              }
      }
  /**
   *  toString() converts the list to a String.
   *  @return a String representation of the list.
   **/

  public String toString() {
    int i;
    Object obj;
    String result = "[  ";

    SListNode cur = head;

    while (cur != null) {
      obj = cur.item;
      result = result + obj.toString() + "  ";
      cur = cur.next;
    }
    result = result + "]";
    return result;
  }


  /**
   *  main() runs test cases on the SList class.  Prints summary
   *  information on basic operations and halts with an error (and a stack
   *  trace) if any of the tests fail.
   **/

  public static void main (String[] args) {
    testEmpty();
    testAfterInsertFront();
    testAfterInsertEnd();
  }

    
  /**
   *  testEmpty() tests toString(), isEmpty(), length(), insertFront(), and
   *  insertEnd() on an empty list.  Prints summary information of the tests
   *  and halts the program if errors are detected.
   **/

  private static void testEmpty() {
    SList lst1 = new SList();
    SList lst2 = new SList();
    System.out.println();
    System.out.println("Here is a list after construction: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  ]"),
              "toString on newly constructed list failed");

    System.out.println("isEmpty() should be true. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == true,
              "isEmpty() on newly constructed list failed");    

    System.out.println("length() should be 0. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 0, 
              "length on newly constructed list failed");    
    lst1.insertFront(new Integer(3));
    System.out.println("Here is a list after insertFront(3) to an empty list: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  3  ]"),
              "InsertFront on empty list failed");
    lst2.insertEnd(new Integer(5));
    System.out.println("Here is a list after insertEnd(5) on an empty list: "
               + lst2.toString());
    TestHelper.verify(lst2.toString().equals("[  5  ]"),
              "insertEnd on empty list failed");
  }

  /**
   *  testAfterInsertFront() tests toString(), isEmpty(), length(),
   *  insertFront(), and insertEnd() after insertFront().  Prints summary
   *  information of the tests and halts the program if errors are detected.
   **/

  private static void testAfterInsertFront() {
    SList lst1 = new SList();
    lst1.insertFront(new Integer(3));
    lst1.insertFront(new Integer(2));
    lst1.insertFront(new Integer(1));
    System.out.println();
    System.out.println("Here is a list after insertFront 3, 2, 1: "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  1  2  3  ]"),
              "InsertFronts on non-empty list failed");
    System.out.println("isEmpty() should be false. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == false,
              "isEmpty() after insertFront failed");    
    System.out.println("length() should be 3. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 3, 
              "length() after insertFront failed");
    lst1.insertEnd(new Integer(4));
    System.out.println("Here is the same list after insertEnd(4): "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  1  2  3  4  ]"),
              "insertEnd on non-empty list failed");
  }
    
  /**
   *  testAfterInsertEnd() tests toString(), isEmpty(), length(),
   *  insertFront(), and insertEnd() after insertEnd().  Prints summary
   *  information of the tests and halts the program if errors are detected.
   **/

  private static void testAfterInsertEnd() {
    SList lst1 = new SList();
    lst1.insertEnd(new Integer(6));
    lst1.insertEnd(new Integer(7));
    System.out.println();
    System.out.println("Here is a list after insertEnd 6, 7: "
               + lst1.toString());
    System.out.println("isEmpty() should be false. It is: " +
               lst1.isEmpty());
    TestHelper.verify(lst1.isEmpty() == false,
              "isEmpty() after insertEnd failed");    
    System.out.println("length() should be 2. It is: " +
               lst1.length());
    TestHelper.verify(lst1.length() == 2, 
              "length() after insertEndfailed");
    lst1.insertFront(new Integer(5));
    System.out.println("Here is the same list after insertFront(5): "
               + lst1.toString());
    TestHelper.verify(lst1.toString().equals("[  5  6  7  ]"),
              "insertFront after insertEnd failed");
  }
}
View Code

Lab4

 完整代码:

DList1.java

package lab4;

/* DList1.java */

/**
 *  A DList1 is a mutable doubly-linked list.  (No sentinel, not
 *  circularly linked.)
 */

public class DList1 {

  /**
   *  head references the first node.
   *  tail references the last node.
   *
   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
   */

  protected DListNode1 head;
  protected DListNode1 tail;
  protected long size;

  /* DList1 invariants:
   *  1)  head.prev == null.
   *  2)  tail.next == null.
   *  3)  For any DListNode1 x in a DList, if x.next == y and x.next != null,
   *      then y.prev == x.
   *  4)  For any DListNode1 x in a DList, if x.prev == y and x.prev != null,
   *      then y.next == x.
   *  5)  The tail can be accessed from the head by a sequence of "next"
   *      references.
   *  6)  size is the number of DListNode1s that can be accessed from the
   *      head by a sequence of "next" references.
   */

  /**
   *  DList1() constructor for an empty DList1.
   */
  public DList1() {
    head = null;
    tail = null;
    size = 0;
  }

  /**
   *  DList1() constructor for a one-node DList1.
   */
  public DList1(int a) {
    head = new DListNode1();
    tail = head;
    head.item = a;
    size = 1;
  }

  /**
   *  DList1() constructor for a two-node DList1.
   */
  public DList1(int a, int b) {
    head = new DListNode1();
    head.item = a;
    tail = new DListNode1();
    tail.item = b;
    head.next = tail;
    tail.prev = head;
    size = 2;
  }

  /**
   *  insertFront() inserts an item at the front of a DList1.
   */
  public void insertFront(int i) {
    // Your solution here.
      DListNode1 Add = new DListNode1(i);      
      Add.next = head;
//      head.prev = Add;
      head = Add;
      size++;
      if(size==1){
          tail = head;
//          tail.prev = null;
      }else if(size==2){
          tail.prev=head;
      }else{head.prev=Add;}
      
  }

  /**
   *  removeFront() removes the first item (and node) from a DList1.  If the
   *  list is empty, do nothing.
   */
  public void removeFront() {
    // Your solution here.
      if(size!=0){
          if(size==1){
              head = null;
              tail=null;
//              tail.prev =null;
//              head.next=null;
//              head.prev=null;              
          }else if(size==2){
          head = head.next;
          tail.prev=null;
          head.prev=null;
          }
          size--;
      }
  }

  /**
   *  toString() returns a String representation of this DList.
   *
   *  DO NOT CHANGE THIS METHOD.
   *
   *  @return a String representation of this DList.
   */
  public String toString() {
    String result = "[  ";
    DListNode1 current = head;
    while (current != null) {
      result = result + current.item + "  ";
      current = current.next;
    }
    return result + "]";
  }

  public static void main(String[] args) {
    // DO NOT CHANGE THE FOLLOWING CODE.

    DList1 l = new DList1();
    System.out.println("### TESTING insertFront ###
Empty list is " + l);

    l.insertFront(9);
    System.out.println("
Inserting 9 at front.
List with 9 is " + l);
    if (l.head == null) {
      System.out.println("head is null.");
    } else {
      if (l.head.item != 9) {
        System.out.println("head.item is wrong.");
      }
      if (l.head.prev != null) {
        System.out.println("head.prev is wrong.");
      }
    }
    if (l.tail == null) {
      System.out.println("tail is null.");
    } else {
      if (l.tail.item != 9) {
        System.out.println("tail.item is wrong.");
      }
      if (l.tail.next != null) {
        System.out.println("tail.next is wrong.");
      }
    }
    if (l.size != 1) {
      System.out.println("size is wrong.");
    }

    l.insertFront(8);
    System.out.println("
Inserting 8 at front.
List with 8 and 9 is " + l);
    if (l.head == null) {
      System.out.println("head is null.");
    } else {
      if (l.head.item != 8) {
        System.out.println("head.item is wrong.");
      }
      if (l.head.prev != null) {
        System.out.println("head.prev is wrong.");
      }
      if (l.head.next != l.tail) {
        System.out.println("head.next is wrong.");
      }
    }
    if (l.tail == null) {
      System.out.println("tail is null.");
    } else {
      if (l.tail.item != 9) {
        System.out.println("tail.item is wrong.");
      }
      if (l.tail.next != null) {
        System.out.println("tail.next is wrong.");
      }
      if (l.tail.prev != l.head) {
        System.out.println("tail.prev is wrong.");
      }
    }
    if (l.size != 2) {
      System.out.println("size is wrong.");
    }



    l = new DList1(1, 2);
    System.out.println("

### TESTING removeFront ###
List with 1 and 2 is "
                       + l);

    l.removeFront();
    System.out.println("
Removing front node.
List with 2 is " + l);
    if (l.head.item != 2) {
      System.out.println("head.item is wrong.");
    }
    if (l.head.prev != null) {
      System.out.println("head.prev is wrong.");
    }
    if (l.tail.item != 2) {
      System.out.println("tail.item is wrong.");
    }
    if (l.tail.next != null) {
      System.out.println("tail.next is wrong.");
    }
    if (l.size != 1) {
      System.out.println("size is wrong.");
    }

    l.removeFront();
    System.out.println("
Removing front node.
Empty list is " + l);
    if (l.head != null) {
      System.out.println("head is wrong.");
    }
    if (l.tail != null) {
      System.out.println("tail is wrong.");
    }
    if (l.size != 0) {
      System.out.println("size is wrong.");
    }

    l.removeFront();
    System.out.println("
Removing front node.
Empty list is " + l);
    if (l.head != null) {
      System.out.println("head is wrong.");
    }
    if (l.tail != null) {
      System.out.println("tail is wrong.");
    }
    if (l.size != 0) {
      System.out.println("size is wrong.");
    }
  }

}
View Code

DListNode1 

package lab4;

/* DListNode1.java */

/**
 *  A DListNode1 is a node in a DList1 (doubly-linked list).
 */

public class DListNode1 {

  /**
   *  item references the item stored in the current node.
   *  prev references the previous node in the DList.
   *  next references the next node in the DList.
   *
   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
   */

  public int item;
  public DListNode1 prev;
  public DListNode1 next;

  /**
   *  DListNode1() constructor.
   */
  DListNode1() {
    item = 0;
    prev = null;
    next = null;
  }

  DListNode1(int i) {
    item = i;
    prev = null;
    next = null;
  }
}
View Code

DList2.java

package lab4;

/* DList2.java */

/**
 *  A DList2 is a mutable doubly-linked list.  Its implementation is
 *  circularly-linked and employs a sentinel (dummy) node at the head
 *  of the list.
 */

public class DList2 {

  /**
   *  head references the sentinel node.
   *
   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
   */

  protected DListNode2 head;
  protected long size;

  /* DList2 invariants:
   *  1)  head != null.
   *  2)  For any DListNode2 x in a DList2, x.next != null.
   *  3)  For any DListNode2 x in a DList2, x.prev != null.
   *  4)  For any DListNode2 x in a DList2, if x.next == y, then y.prev == x.
   *  5)  For any DListNode2 x in a DList2, if x.prev == y, then y.next == x.
   *  6)  size is the number of DListNode2s, NOT COUNTING the sentinel
   *      (denoted by "head"), that can be accessed from the sentinel by
   *      a sequence of "next" references.
   */

  /**
   *  DList2() constructor for an empty DList2.
   */
  public DList2() {
    head = new DListNode2();
    head.item = Integer.MIN_VALUE;
    head.next = head;
    head.prev = head;
    size = 0;
  }

  /**
   *  DList2() constructor for a one-node DList2.
   */
  public DList2(int a) {
    head = new DListNode2();
    head.item = Integer.MIN_VALUE;
    head.next = new DListNode2();
    head.next.item = a;
    head.prev = head.next;
    head.next.prev = head;
    head.prev.next = head;
    size = 1;
  }

  /**
   *  DList2() constructor for a two-node DList2.
   */
  public DList2(int a, int b) {
    head = new DListNode2();
    head.item = Integer.MIN_VALUE;
    head.next = new DListNode2();
    head.next.item = a;
    head.prev = new DListNode2();
    head.prev.item = b;
    head.next.prev = head;
    head.next.next = head.prev;
    head.prev.next = head;
    head.prev.prev = head.next;
    size = 2;
  }

  /**
   *  insertFront() inserts an item at the front of a DList2.
   */
  public void insertFront(int i) {
    // Your solution here.
      DListNode2 add = new DListNode2(i);
      add.next = head.next;
      add.prev = head;
      head.next = add;
      head.next.next.prev=add;    
      size++;
  }

  /**
   *  removeFront() removes the first item (and first non-sentinel node) from
   *  a DList2.  If the list is empty, do nothing.
   */
  public void removeFront() {
    // Your solution here.
      head.next=head.next.next;
      head.next.prev=head;
      if(size!=0){
      size--;
      }
  }

  /**
   *  toString() returns a String representation of this DList.
   *
   *  DO NOT CHANGE THIS METHOD.
   *
   *  @return a String representation of this DList.
   */
  public String toString() {
    String result = "[  ";
    DListNode2 current = head.next;
    while (current != head) {
      result = result + current.item + "  ";
      current = current.next;
    }
    return result + "]";
  }

  public static void main(String[] args) {
    // DO NOT CHANGE THE FOLLOWING CODE.

    DList2 l = new DList2();
    System.out.println("### TESTING insertFront ###
Empty list is " + l);

    l.insertFront(9);
    System.out.println("
Inserting 9 at front.
List with 9 is " + l);
    if (l.head.next.item != 9) {
      System.out.println("head.next.item is wrong.");
    }
    if (l.head.next.prev != l.head) {
      System.out.println("head.next.prev is wrong.");
    }
    if (l.head.prev.item != 9) {
      System.out.println("head.prev.item is wrong.");
    }
    if (l.head.prev.next != l.head) {
      System.out.println("head.prev.next is wrong.");
    }
    if (l.size != 1) {
      System.out.println("size is wrong.");
    }

    l.insertFront(8);
    System.out.println("
Inserting 8 at front.
List with 8 and 9 is " + l);
    if (l.head.next.item != 8) {
      System.out.println("head.next.item is wrong.");
    }
    if (l.head.next.prev != l.head) {
      System.out.println("head.next.prev is wrong.");
    }
    if (l.head.prev.item != 9) {
      System.out.println("head.prev.item is wrong.");
    }
    if (l.head.prev.next != l.head) {
      System.out.println("head.prev.next is wrong.");
    }
    if (l.head.next.next != l.head.prev) {
      System.out.println("l.head.next.next != l.head.prev.");
    }
    if (l.head.prev.prev != l.head.next) {
      System.out.println("l.head.prev.prev != l.head.next.");
    }
    if (l.size != 2) {
      System.out.println("size is wrong.");
    }



    l = new DList2(1, 2);
    System.out.println("

### TESTING removeFront ###
List with 1 and 2 is "
                       + l);

    l.removeFront();
    System.out.println("
List with 2 is " + l);
    if (l.head.next.item != 2) {
      System.out.println("head.next.item is wrong.");
    }
    if (l.head.next.prev != l.head) {
      System.out.println("head.next.prev is wrong.");
    }
    if (l.head.prev.item != 2) {
      System.out.println("head.prev.item is wrong.");
    }
    if (l.head.prev.next != l.head) {
      System.out.println("head.prev.next is wrong.");
    }
    if (l.size != 1) {
      System.out.println("size is wrong.");
    }

    l.removeFront();
    System.out.println("
Empty list is " + l);
    if (l.head.next != l.head) {
      System.out.println("head.next is wrong.");
    }
    if (l.head.prev != l.head) {
      System.out.println("head.prev is wrong.");
    }
    if (l.size != 0) {
      System.out.println("size is wrong.");
    }

    l.removeFront();
    System.out.println("
Empty list is " + l);
    if (l.head.next != l.head) {
      System.out.println("head.next is wrong.");
    }
    if (l.head.prev != l.head) {
      System.out.println("head.prev is wrong.");
    }
    if (l.size != 0) {
      System.out.println("size is wrong.");
    }
  }

}
View Code

DListNode2

package lab4;

/* DListNode2.java */

/**
 *  A DListNode2 is a node in a DList2 (doubly-linked list).
 */

public class DListNode2 {

  /**
   *  item references the item stored in the current node.
   *  prev references the previous node in the DList.
   *  next references the next node in the DList.
   *
   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
   */

  public int item;
  public DListNode2 prev;
  public DListNode2 next;

  /**
   *  DListNode2() constructor.
   */
  DListNode2() {
    item = 0;
    prev = null;
    next = null;
  }

  DListNode2(int i) {
    item = i;
    prev = null;
    next = null;
  }

}
View Code
原文地址:https://www.cnblogs.com/developerchen/p/7145227.html