Java經典問題算法大全
/*【程序1】
題目:古典問題:有一對兔子,從出生後第3個月起每月都生一對兔子,小兔子長到第三個月後每月又生一對兔子,假如兔子都不死,問每月的兔子總數爲多少?
1.程序分析: 兔子的規律爲數列1,1,2,3,5,8,13,21....
*/
package cn.com.flywater.FiftyAlgorthm;
public class FirstRabbit {
public static final int MONTH = 15;
public static void main(String[] args) {
long f1 = 1L, f2 = 1L;
long f;
for(int i=3; i<MONTH; i++) {
f = f2;
f2 = f1 + f2;
f1 = f;
System.out.print("第" + i +"個月的兔子對數: ");
System.out.println(" " + f2);
}
}
}
/*【程序2】
* 做者 若水飛天
題目:判斷101-200之間有多少個素數,並輸出全部素數。
1.程序分析:判斷素數的方法:用一個數分別去除2到sqrt(這個數),若是能被整除,
則代表此數不是素數,反之是素數。 */
package cn.com.flywater.FiftyAlgorthm;
public class SecondPrimeNumber {
public static int count = 0;
public static void main(String[] args) {
for(int i=101;i<200;i++){
boolean b = true;//默認此數就素數
for(int j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
b = false; //此數不是素數
break;
}
}
if(b){
count++;
System.out.print(i+" ");
}
}
System.out.println("/n素數的個數:"+count);
}
}
/*【程序3】
做者 若水飛天
題目:打印出全部的"水仙花數(narcissus number)",所謂"水仙花數"是指一個三位數,
其各位數字立方和等於該數自己。例如:153是一個"水仙花數",由於153=1的三次方+5的三次方+3的三次方。
1.程序分析:利用for循環控制100-999個數,每一個數分解出個位,十位,百位。 */
package cn.com.flywater.FiftyAlgorthm;
public class ThirdNarcissusNum {
static int b, bb, bbb;
public static void main(String[] args) {
for(int num=101; num<1000; num++) {
ThirdNarcissusNum tnn = new ThirdNarcissusNum();
tnn.f(num);
}
}
public void f(int m) {
bbb = m / 100;
bb = (m % 100) / 10;
b = (m % 100) % 10;
if((bbb * bbb * bbb + bb * bb * bb + b * b * b) == m) {
System.out.println(m);
}
}
}
/*【程序4】
做者 若水飛天
題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5。
程序分析:對n進行分解質因數,應先找到一個最小的質數k,而後按下述步驟完成:
(1)若是這個質數恰等於n,則說明分解質因數的過程已經結束,打印出便可。
(2)若是n>k,但n能被k整除,則應打印出k的值,並用n除以k的商,做爲新的正整數你n,重複執行第一步。
(3)若是n不能被k整除,則用k+1做爲k的值,重複執行第一步。 */
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class FourthPrimeFactor {
static int n, k = 2;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
n = s.nextInt();
System.out.print(n + "=" );
FourthPrimeFactor fpf = new FourthPrimeFactor();
fpf.f(n);
}
public void f(int n) {
while(k <= n) {
if(k == n) {
System.out.println(n);
break;
} else if(n > k && n % k == 0) {
System.out.print(k + "*");
n = n / k;
f(n);
break;
} else if(n > k && n % k != 0) {
k++;
f(n);
break;
}
}
}
}
/*【程序5】
做者 若水飛天
題目:利用條件運算符的嵌套來完成此題:學習成績>=90分的同窗用A表示,60-89分之間的用B表示,60分如下的用C表示。
1.程序分析:(a>b)?a:b這是條件運算符的基本例子。 */
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class FifthCondition {
//public static final int S1 = 90;
//public static final int S2 = 60;
static int grade;
public static void main(String[] args) {
Scanner str = new Scanner(System.in);
int s = str.nextInt();
FifthCondition fc = new FifthCondition();
grade = fc.compare(s);
if(grade == 1) {
System.out.print('A');
} else if(grade == 2) {
System.out.print('B');
} else {
System.out.println('C');
}
}
public int compare(int s) {
return s > 90 ? 1
: s > 60 ? 2
:3;
}
}
/*【程序6】
做者 若水飛天
題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。
1.程序分析:利用輾除法。 */
/*
* 在循環中,只要除數不等於0,用較大數除以較小的數,將小的一個數做爲下一輪循環的大數,取得的餘數做爲下一輪循環的較小的數,如此循環直到較小的數的值爲0,返回
* 較大的數,此數即爲最小公約數,最小公倍數爲兩數之積除以最小公倍數。
* */
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class SixthCommonDiviser {
public static void main(String[] args) {
int a, b;
Scanner s1 = new Scanner(System.in);
Scanner s2 = new Scanner(System.in);
a = s1.nextInt();
b = s2.nextInt();
SixthCommonDiviser scd = new SixthCommonDiviser();
int m = scd.division(a, b);
int n = a * b / m;
System.out.println("最大公約數: " + m);
System.out.println("最小公倍數: " + n);
}
public int division(int x, int y) {
int t;
if(x < y) {
t = x;
x = y;
y = t;
}
while(y != 0) {
if(x == y) return 1;
else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}
}
/*【程序7】
做者 若水飛天
題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
1.程序分析:利用while語句,條件爲輸入的字符不爲 '/n '. */
package cn.com.flywater.FiftyAlgorthm;
import java.util.*;
public class SeventhCharacterStatistics {
static int digital = 0;
static int character = 0;
static int other = 0;
static int blank = 0;
public static void main(String[] args) {
char[] ch = null;
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
ch = s.toCharArray();
for(int i=0; i<ch.length; i++) {
if(ch[i] >= '0' && ch[i] <= '9') {
digital ++;
} else if((ch[i] >= 'a' && ch[i] <= 'z') || ch[i] > 'A' && ch[i] <= 'Z') {
character ++;
} else if(ch[i] == ' ') {
blank ++;
} else {
other ++;
}
}
System.out.println("數字個數: " + digital);
System.out.println("英文字母個數: " + character);
System.out.println("空格個數: " + blank);
System.out.println("其餘字符個數:" + other );
}
}
/*【程序8】
做者 若水飛天
題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。
*/
/*
* 算法: 定義一個變量b, 賦初值爲0;定義一變量sum, 賦初值爲0,
* 進入循環後,將a + b 的值賦給b,將sum + b 的值賦給sum;
* 同時,將a 增長十倍, ++ i; 繼續循環;
* 循環結束後,輸出sum 的值。
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class EightPlus {
static long a = 2, b = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i = 0;
long sum = 0;
while(i < n) {
b = b + a;
sum = sum + b;
a = a * 10;
++ i;
}
System.out.println("input number: " + n);
System.out.println(sum);
}
}
/*【程序9】
題目:一個數若是剛好等於它的因子之和,這個數就稱爲 "完數 "。例如6=1+2+3.編程 找出1000之內的全部完數。
*/
package cn.com.flywater.FiftyAlgorthm;
public class NinthWanshu {
public static void main(String[] args) {
System.out.println("1到1000的完數有: ");
for(int i=1; i<1000; i++) {
int t = 0;
for(int j=1; j<= i/2; j++) {
if(i % j == 0) {
t = t + j;
}
}
if(t == i) {
System.out.print(i + " ");
}
}
}
}
/*【程序10】
做者 若水飛天
題目:一球從100米高度自由落下,每次落地後反跳回原高度的一半;再落下,
求它在 第10次落地時,共通過多少米?第10次反彈多高?
*/
package cn.com.flywater.FiftyAlgorthm;
public class TenthTreeFall {
static double height = 100;
static double distance = 100;
public static void main(String[] args) {
for(int i=1; i<10; i++) {
distance = distance + height;
height = height / 2;
}
System.out.println("路程:" + distance);
System.out.println("高度:" + height / 2);
}
}
/*【程序11】
* 做者 若水飛天
題目:有一、二、三、4個數字,能組成多少個互不相同且無重複數字的三位數?都是多少?
1.程序分析:可填在百位、十位、個位的數字都是一、二、三、4。組成全部的排列後再去 掉不知足條件的排列。
*/
/*算法:3個for循環加一個if語句;
*
*/
package cn.com.flywater.FiftyAlgorthm;
public class EleventhNumberRange {
public static void main(String[] args) {
int count = 0;
for(int x=1; x<5; x++) {
for(int y=1; y<5; y++) {
for(int z=1; z<5; z++) {
if(x != y && y != z && x != z) {
count ++;
System.out.print(x*100 + y*10 + z + " ");
if(count % 4 == 0) {
System.out.println();
}
}
}
}
}
System.out.println("共有" + count + "個三位數");
}
}
/*【程序12】
* 做者 若水飛天
題目:企業發放的獎金根據利潤提成。利潤(I)低於或等於10萬元時,獎金可提10%;
利潤高於10萬元,低於20萬元時,低於10萬元的部分按10%提成,高於10萬元的部分,
可可提成7.5%;20萬到40萬之間時,高於20萬元的部分,
可提成5%;40萬到60萬之間時高於40萬元的部分,可提成3%;
60萬到100萬之間時,高於60萬元的部分,可提成1.5%,高於100萬元時,超過100萬元的部分按1%提成,
從鍵盤輸入當月利潤I,求應發放獎金總數?
1.程序分析:請利用數軸來分界,定位。注意定義時需把獎金定義成長整型。
*/
/*注意: 要精確到小數點後多少位,用 DecimalFormat df = new DecimalFormat("#0.0000");
*
*/
package cn.com.flywater.FiftyAlgorthm;
import java.text.DecimalFormat;
import java.util.*;
public class TwelfthProfitAward {
static double profit = 0;
static double award = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
profit = s.nextInt();
System.out.println("輸入的利潤是" + profit + "萬");
if(profit > 0 && profit <= 10) {
award = profit * 0.1;
} else if(profit > 10 && profit <= 20) {
award = 10 * 0.1 + (profit - 10) * 0.075;
} else if(profit > 20 && profit <= 40) {
award = 10 * 0.1 + 10 * 0.075 + (profit - 20) * 0.05;
} else if(profit > 40 && profit <= 60) {
award = 10 * 0.1 + 10 * 0.075 + 20 * 0.05 + (profit - 40) * 0.03;
} else if(profit > 60 && profit <= 100) {
award = 20 * 0.175 + 20 * 0.05 + 20 * 0.03 + (profit - 60) * 0.015;
} else if(profit > 100) {
award = 20 * 0.175 + 40 * 0.08 + 40 * 0.015 + (profit - 100) * 0.01;
}
DecimalFormat df = new DecimalFormat("#0.00000");
System.out.println("應該提取的獎金是 " + df.format(award) + "萬");
}
}
/*【程序13】
* 做者 若水飛天
題目:一個整數,它加上100後是一個徹底平方數,再加上168又是一個徹底平方數,請問該數是多少?
1.程序分析:在10萬之內判斷,先將該數加上100後再開方,再將該數加上268後再開方,
若是開方後的結果知足以下條件,便是結果。請看具體分析:
*/
package cn.com.flywater.FiftyAlgorthm;
public class ThirteenthTwiceSqrt {
public static void main(String[] args) {
for(long l=1L; l<100000; l++) {
if(Math.sqrt((long)(l+100)) % 1 == 0) {
if(Math.sqrt((long)(l+268)) % 1 == 0) {
System.out.println(l + "加100是一個徹底平方數,再加168又是一個徹底平方數");
}
}
}
}
}
*【程序14】
* 做者 若水飛天
題目:輸入某年某月某日,判斷這一天是這一年的第幾天?
1.程序分析:以3月5日爲例,應該先把前兩個月的加起來,
而後再加上5天即本年的第幾天,特殊狀況,閏年且輸入月份大於3時需考慮多加一天。
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
import java.io.*;
public class FourteenthYearMonthDay {
public static void main(String[] args) {
int year, month, day;
int days = 0;
int d = 0;
FourteenthYearMonthDay fymd = new FourteenthYearMonthDay();
System.out.print("Input the year:");
year =fymd.input();
System.out.print("Input the month:");
month = fymd.input();
System.out.print("Input The Day:");
day = fymd.input();
if (year < 0 || month < 0 || month > 12 || day < 0 || day > 31) {
System.out.println("Input error, please run this program again!");
System.exit(0);
}
for (int i=1; i <month; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
//d += days;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
//d += days;
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
days = 29;
} else {
days = 28;
}
//d += days;
break;
}
d += days;
}
System.out.println(year + ":" + month + ":" + day + "是今年的第" + (d+day) + "天。");
}
public int input() {
int value = 0;
Scanner s = new Scanner(System.in);
value = s.nextInt();
return value;
}
}
/*【程序15】
* 做者 若水飛天
題目:輸入三個整數x,y,z,請把這三個數由小到大輸出。
1.程序分析:咱們想辦法把最小的數放到x上,先將x與y進行比較,若是x> y則將x與y的值進行交換,而後再用x與z進行比較,若是x> z則將x與z的值進行交換,這樣能使x最小。
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.*;
public class FifteenthNumberCompare {
public static void main(String[] args) {
FifteenthNumberCompare fnc = new FifteenthNumberCompare();
int a, b, c;
System.out.println("Input 3 numbers:");
a = fnc.input();
b = fnc.input();
c = fnc.input();
//
// fnc.compare(a, b);//方法調用不能經過改變形參的值來改變實參的值
// fnc.compare(b, c);// 這種作法是錯的
// fnc.compare(a, c);
//System.out.println("result:" + a +" " + b + " " + c);// 沒有改變
if(a > b) {
int t = a;
a = b;
b = t;
}
if(a > c) {
int t = a;
a = c;
c = t;
}
if(b > c) {
int t = b;
b = c;
c = t;
}
System.out.println( a + " " + b + " " + c);
}
public int input() {
int value = 0;
Scanner s = new Scanner(System.in);
value = s.nextInt();
return value;
}
public void compare(int x, int y) {//此方法沒用
if(x > y) {
int t = x;
x = y;
y = t;
}
}
}
/*【程序16】
* 做者 若水飛天
*題目:輸出9*9口訣。
*1.程序分析:分行與列考慮,共9行9列,i控制行,j控制列。
**/
package cn.com.flywater.FiftyAlgorthm;
public class SixteenthMultiplicationTable {
public static void main(String[] args) {
for(int i=1; i<10; i++) {
for(int j=1; j<=i; j++) {
System.out.print(j + "*" + i + "=" + j*i + " " );
}
System.out.println();
}
}
}
//【程序17】
//做者 若水飛天
//題目:猴子吃桃問題:猴子第一天摘下若干個桃子,立即吃了一半,還不癮,
//又多吃了一個 次日早上又將剩下的桃子吃掉一半,又多吃了一個。
//之後天天早上都吃了前一天剩下 的一半零一個。到第10天早上想再吃時,
//見只剩下一個桃子了。求第一天共摘了多少。
//1.程序分析:採起逆向思惟的方法,從後往前推斷。
package cn.com.flywater.FiftyAlgorthm;
public class SeventeenthMonkeyPeach {
public static void main(String[] args) {
int lastdayNum = 1;
for(int i=2; i<=10; i++) {
lastdayNum = (lastdayNum+1) * 2;
}
System.out.println("猴子第一天摘了 " + lastdayNum + " 個桃子");
}
}
/*【程序18】
* 做者 若水飛天
題目:兩個乒乓球隊進行比賽,各出三人。甲隊爲a,b,c三人,乙隊爲x,y,z三人。
已抽籤決定比賽名單。有人向隊員打聽比賽的名單。a說他不和x比,c說他不和x,z比,請編程序找出三隊賽手的名單。
*/
/*
* 這個程序寫得很很差,是知道結果後拼湊起來的,還不如直接寫輸出語句加上結果來的好。
*/
package cn.com.flywater.FiftyAlgorthm;
public class EighteenthPingpong {
static char[] m = { 'a', 'b', 'c' };
static char[] n = { 'x', 'y', 'z' };
public static void main(String[] args) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < n.length; j++) {
if (m[i] == 'a' && n[j] == 'x') {
continue;
} else if (m[i] == 'a' && n[j] == 'y') {
continue;
} else if ((m[i] == 'c' && n[j] == 'x')
|| (m[i] == 'c' && n[j] == 'z')) {
continue;
} else if ((m[i] == 'b' && n[j] == 'z')
|| (m[i] == 'b' && n[j] == 'y')) {
continue;
} else
System.out.println(m[i] + " vs " + n[j]);
}
}
}
}
題目:打印出以下圖案(菱形)
*
***
*****
*******
*****
***
*
1.程序分析:先把圖形分紅兩部分來看待,前四行一個規律,後三行一個規律,利用雙重 for循環,
第一層控制行,第二層控制列。
*/
/*上半部分循環變量的控制方法是
* for(int i=0; i<(HEIGHT+1) / 2; i++) {
for(int j=1; j<WIDTH/2-i; j++) {
for(int k=1; k<(i+1)*2; k++) {
下半部分循環變量的控制方法是
for(int i=1; i<=HEIGHT/2; i++) {
for(int j=1; j<=i; j++) {
* for(int k=1; k<=WIDTH-2*i-1; k++) {
*/
package cn.com.flywater.FiftyAlgorthm;
public class NineteenthPrintRhombic {
static final int HEIGHT = 7;
static final int WIDTH = 8;
public static void main(String[] args) {
for(int i=0; i<(HEIGHT+1) / 2; i++) {
for(int j=1; j<WIDTH/2-i; j++) {
System.out.print(" ");
}
for(int k=1; k<(i+1)*2; k++) {
System.out.print('*');
}
System.out.println();
}
for(int i=1; i<=HEIGHT/2; i++) {
for(int j=1; j<=i; j++) {
System.out.print(" ");
}
for(int k=1; k<=WIDTH-2*i-1; k++) {
System.out.print('*');
}
System.out.println();
}
}
}
上半部分第二重循環應改成: for(int j=0; j<WIDTH/2-i; j++)
上半部分第三重循環應改成: for(int k=1; k<=WIDTH-2*i; k++)
/*【程序20】
* 做者 若水飛天
題目:有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。
1.程序分析:請抓住分子與分母的變化規律。
*/
package cn.com.flywater.FiftyAlgorthm;
import java.text.DecimalFormat;
public class TwentiethFractionSum {
public static void main(String[] args) {
int x = 2, y = 1, t;
double sum = 0;
DecimalFormat df = new DecimalFormat("#0.0000");
for(int i=1; i<=20; i++) {
sum += (double)x / y;
t = y;
y = x;
x = y + t;
System.out.println("第 " + i + " 次相加,和是 " + df.format(sum));
}
}
/*【程序21】
* 做者 若水飛天
題目:求1+2!+3!+...+20!的和
1.程序分析:此程序只是把累加變成了累乘。
*/
package cn.com.flywater.FiftyAlgorthm;
public class Twenty_firstFactorialSum {
static long sum = 0;
static long fac = 0;
public static void main(String[] args) {
long sum = 0;
long fac = 1;
for(int i=1; i<=10; i++) {
fac = fac * i;
sum += fac;
}
System.out.println(sum);
}
}
/*【程序22】
* 做者 若水飛天
題目:利用遞歸方法求5!。
1.程序分析:遞歸公式:fn=fn_1*4!
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Twenty_secondFactorialRecursion {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Twenty_secondFactorialRecursion tfr = new Twenty_secondFactorialRecursion();
System.out.println(tfr.recursion(n));
}
public long recursion(int n) {
long value = 0 ;
if(n ==1 || n == 0) {
value = 1;
} else if(n > 1) {
value = n * recursion(n-1);
}
return value;
}
}
/*【程序23】
* 做者 : 若水飛天
題目:有5我的坐在一塊兒,問第五我的多少歲?他說比第4我的大2歲。
問第4我的歲數,他說比第3我的大2歲。問第三我的,又說比第2人大兩歲。
問第2我的,說比第一我的大兩歲。最後問第一我的,他說是10歲。請問第五我的多大?
1.程序分析:利用遞歸的方法,遞歸分爲回推和遞推兩個階段。
要想知道第五我的歲數,需知道第四人的歲數,依次類推,推到第一人(10歲),再往回推。
**/
package cn.com.flywater.FiftyAlgorthm;
public class Twenty_thirdPeopleAge {
public static void main(String[] args) {
int age = 10;
for(int i=2; i<=5; i++) {
age += 2;
}
System.out.println(age);
}
}
/*【程序24】
* 做者 若水飛天
題目:給一個很少於5位的正整數,
要求:1、求它是幾位數,2、逆序打印出各位數字。
說明: 這個算法實現雖然實現了這個功能,但不健壯,當輸入字符是,會出現異常。
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Twenty_fourthNumber {
public static void main(String[] args) {
Twenty_fourthNumber tn = new Twenty_fourthNumber();
Scanner s = new Scanner(System.in);
long a = s.nextLong();
if(a < 0 || a > 100000) {
System.out.println("Error Input, please run this program Again");
System.exit(0);
}
if(a >=0 && a <=9) {
System.out.println( a + "是一位數");
System.out.println("按逆序輸出是" + '/n' + a);
} else if(a >= 10 && a <= 99) {
System.out.println(a + "是二位數");
System.out.println("按逆序輸出是" );
tn.converse(a);
} else if(a >= 100 && a <= 999) {
System.out.println(a + "是三位數");
System.out.println("按逆序輸出是" );
tn.converse(a);
} else if(a >= 1000 && a <= 9999) {
System.out.println(a + "是四位數");
System.out.println("按逆序輸出是" );
tn.converse(a);
} else if(a >= 10000 && a <= 99999) {
System.out.println(a + "是五位數");
System.out.println("按逆序輸出是" );
tn.converse(a);
}
}
public void converse(long l) {
String s = Long.toString(l);
char[] ch = s.toCharArray();
for(int i=ch.length-1; i>=0; i--) {
System.out.print(ch[i]);
}
}
}
這個算法實在太土了,也許只有我若水飛天才會這樣寫,
下面寫一個優雅一點的
import java.util.Scanner;
public class Twenty_fourthNumber {
public static void main(String[] args) {
Twenty_fourthNumber tn = new Twenty_fourthNumber();
Scanner s = new Scanner(System.in);
long a = s.nextLong();
String s = Long.toString(l);
char[] ch = s.toCharArray();
System.out.println(a + "是" + ch.length + 「位數」);
for(int i=ch.length-1; i>=0; i--) {
System.out.print(ch[i]);
}
}
}
/*【程序25】
* 做者 若水飛天
題目:一個5位數,判斷它是否是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。
**/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Twenty_fifthPalindrom {
static int[] a = new int[5];
static int[] b = new int[5];
public static void main(String[] args) {
boolean is =false;
Scanner s = new Scanner(System.in);
long l = s.nextLong();
if (l > 99999 || l < 10000) {
System.out.println("Input error, please input again!");
l = s.nextLong();
}
for (int i = 4; i >= 0; i--) {
a[i] = (int) (l / (long) Math.pow(10, i));
l =(l % ( long) Math.pow(10, i));
}
System.out.println();
for(int i=0,j=0; i<5; i++, j++) {
b[j] = a[i];
}
for(int i=0,j=4; i<5; i++, j--) {
if(a[i] != b[j]) {
is = false;
break;
} else {
is = true;
}
}
if(is == false) {
System.out.println("is not a Palindrom!");
} else if(is == true) {
System.out.println("is a Palindrom!");
}
}
}
這個更好,不限位數
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("請輸入一個正整數:");
long a = s.nextLong();
String ss = Long.toString(a);
char[] ch = ss.toCharArray();
boolean is =true;
int j=ch.length;
for(int i=0; i<j/2; i++) {
if(ch[i]!=ch[j-i-1]){is=false;}
}
if(is==true){System.out.println("這是一個迴文數");}
else {System.out.println("這不是一個迴文數");}
}
/*【程序26】
* 做者 若水飛天
題目:請輸入星期幾的第一個字母來判斷一下是星期幾,
若是第一個字母同樣,則繼續 判斷第二個字母。
1.程序分析:用狀況語句比較好,若是第一個字母同樣,
則判斷用狀況語句或if語句判斷第二個字母。
此程序雖然實現了基本功能,但必須嚴格按照題目的要求輸入,不然程序沒法執行
**/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Twenty_sixthWeek {
Scanner s = new Scanner(System.in);
public static void main(String[] args) {
Twenty_sixthWeek tw = new Twenty_sixthWeek();
char ch = tw.getChar();
switch(ch) {
case 'M':
System.out.println("Monday");
break;
case 'W':
System.out.println("Wednesday");
break;
case 'F':
System.out.println("Friday");
break;
case 'T': {
System.out.println("please input the second letter!");
char ch2 = tw.getChar();
if(ch2 == 'U') {System.out.println("Tuesday"); }
else if(ch2 == 'H') {System.out.println("Thursday"); }
};
break;
case 'S': {
System.out.println("please input the scecond letter!");
char ch2 = tw.getChar();
if(ch2 == 'U') {System.out.println("Sunday"); }
else if(ch2 == 'A') {System.out.println("Saturday"); }
};
break;
}
}
public char getChar() {
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'A' || ch>'Z') {
System.out.println("Input error, please input a capital letter");
getChar();
}
return ch;
}
}
/*【程序27】
* 做者 若水飛天
題目:求100以內的素數
1.程序分析:判斷素數的方法:用一個數分別去除2到sqrt(這個數),
若是能被整除, 則代表此數不是素數,反之是素數。
**/
package cn.com.flywater.FiftyAlgorthm;
public class Twenty_seventhPrimeNumber {
public static void main(String[] args) {
boolean b =false;
int count = 0;
for(int i=2; i<100; i+=1) {
for(int j=2; j<=Math.sqrt(i); j++) {
if(i % j == 0) {
b = false;
break;
} else{
b = true;
}
}
if(b == true) {
count ++;
System.out.print(i + " ");
}
}
System.out.println('/n' + "The number of PrimeNumber is :" + count);
}
}
/*【程序28】
* 做者 若水飛天
題目:對10個數進行排序
1.程序分析:能夠利用選擇法,即從後9個比較過程當中,
選擇一個最小的與第一個元素交換, 下次類推,
即用第二個元素與後8個進行比較,並進行交換。
**/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Twehty_eighthNumberSort {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] a = new int[10];
for(int i=0; i<10; i++) {
a[i] = s.nextInt();
}
for(int i=0; i<10; i++) {
for(int j=i+1; j<10; j++) {
if(a[i] > a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for(int i=0; i<10; i++) {
System.out.print(a[i] + " ");
}
}
}
/*【程序29】
* 做者 若水飛天
* 按程序分析,好像只是求主對角線的和
題目:求一個3*3矩陣對角線元素之和
1.程序分析:利用雙重for循環控制輸入二維數組,再將a[i][i]累加後輸出。
**/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Twenty_ninthCrossSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] a = new int[3][3];
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("輸入的3 * 3 矩陣是:");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int sum = 0;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
if(i == j) {
sum += a[i][j];
}
}
}
System.out.println("對角線和是 " + sum);
}
}
/*【程序30】
* 做者 若水飛天
題目:有一個已經排好序的數組。現輸入一個數,要求按原來的規律將它插入數組中。
1. 程序分析:首先判斷此數是否大於最後一個數,
而後再考慮插入中間的數的狀況,插入後此元素以後的數,依次後移一個位置。
**/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class ThirtiethInsert {
public static void main(String[] args) {
int[] a = new int[]{1, 2, 3, 4, 5, 6, 7};
int[] b = new int[a.length+1];
int t1 =0, t2 = 0;
int i =0;
Scanner s= new Scanner(System.in);
int num = s.nextInt();
/*
* 定義兩個數組a,b,一個a的長度比另外一個b大1, a看作是
* 已經排好序的。
* 接下來的過程是
* 1: 若是num 比最後一個數大,把num賦值給數組b的最後一個數
* 再按順序把a 的每一個元素賦給b
* 2: 不然(num 不比a 的最後一個數大),
* 若是a 的元素比num 小,則將這些元素按順序賦給b
* 將num 賦給比num大的b數組的元素,
* 跳出第一個for循環。
* 3: 定義一個循環控制變量,從num傳給數組後num的下標值加一開始;
* 直到b的結尾,將剩下的a 的值賦給b,賦值的過程是b[j] = a[i-1];
*
*/
if(num >= a[a.length-1]) {
b[b.length-1] = num;
for(i=0; i<a.length; i++) {
b[i] = a[i];
}
} else {
for(i=0; i<a.length; i++) {
if(num >= a[i]) {
b[i] = a[i];
} else {
b[i] = num;
break;
}
}
for(int j=i+1; j<b.length; j++) {
b[j] = a[j-1];
}
}
for (i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
/*【程序21】
* 做者 若水飛天
題目:求1+2!+3!+...+20!的和
1.程序分析:此程序只是把累加變成了累乘。
*/
package cn.com.flywater.FiftyAlgorthm;
public class Twenty_firstFactorialSum {
static long sum = 0;
static long fac = 0;
public static void main(String[] args) {
long sum = 0;
long fac = 1;
for(int i=1; i<=10; i++) {
fac = fac * i;
sum += fac;
}
System.out.println(sum);
}
}
/*【程序32】
* 做者 若水飛天
題目:取一個整數a從右端開始的4~7位。
程序分析:能夠這樣考慮:
(1)先使a右移4位。
(2)設置一個低4位全爲1,其他全爲0的數。可用~(~0 < <4)
(3)將上面兩者進行&運算。
**/
/*這個題我不會作,若有高手路過,還望指點
*
*/
package cn.com.flywater.FiftyAlgorthm;
public class Thirty_secondFS {
public static void main(String[] args) {
}
}
我沒有用提示的方法,採用了字串截取。
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean is =true;
System.out.print("請輸入一個7位以上的正整數:");
long a = s.nextLong();
String ss = Long.toString(a);
char[] ch = ss.toCharArray();
int j=ch.length;
if (j<7){System.out.println("輸入錯誤!");}
else {
System.out.println("截取從右端開始的4~7位是:"+ch[j-7]+ch[j-6]+ch[j-5]+ch[j-4]);
}
}
【程序33】
* 做者 若水飛天
題目:打印出楊輝三角形(要求打印出10行以下圖)
1.程序分析:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
*/
/*
* 網上千篇一概是這種寫法,我也沒有什麼創新,
* a[i][j]=a[i-1][j]+a[i-1][j-1] 就是這個程序的核心
* 定義的是二維數組,爲了使輸出的結果看起來漂亮一點
* 能夠用for(int k=0; k<2*(10-i)-1; k++)控制輸出的空格
* 這個循環是在控制行數的循環裏面,控制列數的循環外面。
* 記得在輸出菱形時爲了控制下半部分的輸出,在下拼命的寫出
* for(int k=1; k<=WIDTH-2*i-1; k++) 纔算了事。
*/
package cn.com.flywater.FiftyAlgorthm;
public class Thirty_thirdYangTriangle {
public static void main(String[] args) {
int[][] a = new int[10][10];
for(int i=0; i<10; i++) {
a[i][i] = 1;
a[i][0] = 1;
}
for(int i=2; i<10; i++) {
for(int j=1; j<i; j++) {
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
}
for(int i=0; i<10; i++) {
for(int k=0; k<2*(10-i)-1; k++) {
System.out.print(" ");
}
for(int j=0; j<=i; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
/*【程序34】
* 做者 若水飛天
題目:輸入3個數a,b,c,按大小順序輸出。
1.程序分析:利用指針方法。
*/
/*
* 惋惜,Java好像沒有指針
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Thirty_forthCompare {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();
if(a < b) {
int t = a;
a = b;
b = t;
}
if(a < c) {
int t = a;
a = c;
c = t;
}
if(b < c) {
int t = b;
b = c;
c = t;
}
System.out.println("從大到小的順序輸出:");
System.out.println(a + " " + b + " " + c);
}
}
/*【程序35】
* 做者 若水飛天
題目:輸入數組,最大的與第一個元素交換,最小的與最後一個元素交換,輸出數組。
**/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Thirty_fifthSwop {
static final int N = 8;
public static void main(String[] args) {
int[] a = new int [N];
Scanner s = new Scanner(System.in);
int index1 = 0, index2 = 0;
System.out.println("please input numbers");
for(int i=0; i<N; i++) {
a[i] = s.nextInt();
System.out.print(a[i] + " ");
}
int max =a[0], min = a[0];
for(int i=0; i<a.length; i++) {
if(a[i] > max) {
max = a[i];
index1 = i;
}
if(a[i] < min) {
min = a[i];
index2 = i;
}
}
if(index1 != 0) {
int temp = a[0];
a[0] = a[index1];
a[index1] = temp;
}
if(index2 != a.length-1) {
int temp = a[a.length-1];
a[a.length-1] = a[index2];
a[index2] = temp;
}
System.out.println("after swop:");
for(int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
/*【程序36】
* 做者 若水飛天
題目:有n個整數,使其前面各數順序向後移m個位置,最後m個數變成最前面的m個數
**/
/*
* 這個題不知道有什麼好辦法,比較直接方法的是把這個數組分紅兩個數組,
* 再將兩個數組合起來,但若是不控制好數組的下標,就會帶來不少麻煩。
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Thirty_sixthBackShift {
public static final int N =10;
public static void main(String[] args) {
int[] a = new int[N];
Scanner s = new Scanner(System.in);
System.out.println("please input array a, ten numbers:");
for(int i=0; i<a.length; i++) {
a[i] = s.nextInt();
}
System.out.println("please input m , one number:");
int m = s.nextInt();
int[] b = new int[m];
int[] c = new int[N-m];
for(int i=0; i<m; i++) {
b[i] = a[i];
}
for(int i=m,j=0; i<N; i++,j++) {
c[j] = a[i];
}
for(int i=0; i<N-m; i++) {
a[i] = c[i];
}
for(int i=m,j=0; i<N; i++,j++) {
a[i] = b[j];
}
for(int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
/*【程序37】
* 做者 若水飛天
題目:有n我的圍成一圈,順序排號。從第一我的開始報數(從1到3報數),
凡報到3的人退出圈子,問最後留下的是原來第幾號的那位。
**/
/*
* 這個程序是徹底抄別人的
*/
package cn.com.flywater.FiftyAlgorthm;
import java.util.Scanner;
public class Thirty_sevenCount3Quit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
boolean[] arr = new boolean[n];
for(int i=0; i<arr.length; i++) {
arr[i] = true;//下標爲TRUE時說明還在圈裏
}
int leftCount = n;
int countNum = 0;
int index = 0;
while(leftCount > 1) {
if(arr[index] == true) {//當在圈裏時
countNum ++; //報數遞加
if(countNum == 3) {//報道3時
countNum =0;//從零開始繼續報數
arr[index] = false;//此人退出圈子
leftCount --;//剩餘人數減一
}
}
index ++;//每報一次數,下標加一
if(index == n) {//是循環數數,當下標大於n時,說明已經數了一圈,
index = 0;//將下標設爲零從新開始。
}
}
for(int i=0; i<n; i++) {
if(arr[i] == true) {
System.out.println(i);
}
}
}
}
/*【程序38】
* 做者 若水飛天
題目:寫一個函數,求一個字符串的長度,在main函數中輸入字符串,並輸出其長度。
*/
package cn.com.flywater.FiftyAlgorthm;
public class Thirty_eighthStringLength {
public static void main(String[] args) {
String s = "jdfifdfhfhuififffdfggee";
System.out.print("字符串的長度是:");
System.out.println(s.length());
}
}
*【程序39】
* 做者 若水飛天
題目:編寫一個函數,輸入n爲偶數時,調用函數求1/2+1/4+...+1/n,
當輸入n爲奇數時,調用函數1/1+1/3+...+1/n(利用指針函數)
**/
package cn.com.flywater.FiftyAlgorthm;
import java.text.DecimalFormat;
import java.util.*;
public class Thirty_ninthFactionSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
DecimalFormat df = new DecimalFormat("#0.00000");
System.out.println( n +" **** result " + df.format(sum(n)));
}
public static double sum(int n) {
double result = 0;
if(n % 2 == 0) {
for(int i=2; i<=n; i+=2) {
result += (double)1 / n;
}
} else {
for(int i=1; i<=n; i+=2) {
result += (double)1 / i ;
}
}
return result;
}
}
/*【程序40】
* 做者 若水飛天
題目:字符串排序。
**/
package cn.com.flywater.FiftyAlgorthm;
public class FortiethStringSort {
public static void main(String[] args) {
String temp = null;
String[] s = new String[5];
s[0] = "china".toLowerCase();
s[1] = "apple".toLowerCase();
s[2] = "MONEY".toLowerCase();
s[3] = "BOOk".toLowerCase();
s[4] = "yeah".toLowerCase();
/*
for(int i=0; i<s.length; i++) {
for(int j=i+1; j<s.length; j++) {
if(s[i].compareToIgnoreCase(s[j]) > 0) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}*/
for(int i=0; i<s.length; i++) {
for(int j=i+1; j<s.length; j++) {
if(compare(s[i], s[j]) == false) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for(int i=0; i<s.length; i++) {
System.out.println(s[i]);
}
}
static boolean compare(String s1, String s2) {
boolean result = true;
for(int i=0; i<s1.length() && i<s2.length(); i++) {
if(s1.charAt(i) > s2.charAt(i)) {
result = false;
break;
} else if(s1.charAt(i) <s2.charAt(i)) {
result = true;
break;
} else {
if(s1.length() < s2.length()) {
result = true;
} else {
result = false;
}
}
}
return result;
}
}
LinkedList類裏面較重要的方法就是"addBefore(){}"和"private void remove(DNode <T> curr){}"
不少方法都與它倆有關係!!
下面的代碼是個雙向循環鏈表,在LinkedList裏抄的...
package LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class MyLinkedList<T> {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private DNode<T> header;
private int listSize;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public MyLinkedList() {
header = new DNode<T>();
listSize = 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private static class DNode<T> {
T nodeValue;
DNode<T> prev;
DNode<T> next;
public DNode() { // for header
nodeValue = null;
prev = this; // left
next = this; // right
}
public DNode(T item) {
nodeValue = item;
prev = this;
next = this;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public boolean isEmpty() {
return (header.prev == header || header.next == header);
}
public int size() {
return listSize;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private DNode<T> addBefore(DNode<T> curr, T item) {
DNode<T> newNode, prevNode;
newNode = new DNode<T>(item);
prevNode = curr.prev;
newNode.prev = prevNode;
newNode.next = curr;
prevNode.next = newNode;
curr.prev = newNode;
return newNode;
}
public boolean add(T item) {
addBefore(header, item);
listSize++;
return true;
}
public void addFirst(T item) {
addBefore(header.next, item);
listSize++;
}
public void addLast(T item) {
addBefore(header, item);
listSize++;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private void remove(DNode<T> curr) {
if(curr.next == curr) return;
DNode<T> prevNode = curr.prev, nextNode = curr.next;
prevNode.next = nextNode;
nextNode.prev= prevNode;
}
public boolean remove(Object o) {
for(DNode<T> p = header.next; p != header; p = p.next) {
if(o.equals(p.nodeValue)) {
remove(p);
listSize--;
return true;
}
}
return false;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void printList() {
for(DNode<T> p = header.next; p != header; p = p.next)
System.out.println(p.nodeValue);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class MyIterator implements Iterator<T> {
public DNode<T> nextNode = header.next;
public DNode<T> lastReturned = header;
public boolean hasNext() {
return nextNode != header;
}
public T next() {
if(nextNode == header)
throw new NoSuchElementException("");
lastReturned = nextNode;
nextNode = nextNode.next;
return lastReturned.nodeValue;
}
public void remove() {
if(lastReturned == header)
throw new IllegalStateException("");
MyLinkedList.this.remove(lastReturned);
lastReturned = header;
listSize--;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class MyListIterator extends MyIterator implements ListIterator<T> {
private int nextIndex;
MyListIterator(int index) {
if(index < 0 || index > listSize)
throw new IndexOutOfBoundsException("");
//若是index小於listSize/2,就從表頭開始查找定位,不然就從表尾開始查找定位
if(index < (listSize >> 1)) {
nextNode = header.next;
for(nextIndex = 0; nextIndex < index; nextIndex++)
nextNode = nextNode.next;
}else {
nextNode = header;
for(nextIndex = listSize; nextIndex > index; nextIndex--)
nextNode = nextNode.prev;
}
}
public boolean hasPrevious() {
return nextIndex != 0;
//return nextNode.prev != header;
}
public T previous() {
if (nextIndex == 0)
throw new NoSuchElementException("no");
lastReturned = nextNode = nextNode.prev;
nextIndex--;
return lastReturned.nodeValue;
}
public void remove() {
if(lastReturned == header)
throw new IllegalStateException("");
MyLinkedList.this.remove(lastReturned);
nextIndex--;
listSize--;
if(lastReturned == nextNode)
nextNode = nextNode.next;
lastReturned = header;
}
public void add(T item) {
MyLinkedList.this.addBefore(nextNode, item);
nextIndex++;
listSize++;
lastReturned = header;
}
public void set(T item) {
if (lastReturned == header)
throw new IllegalStateException();
lastReturned.nodeValue = item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public Iterator<T> iterator() {
return new MyIterator();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public ListIterator<T> listIterator(int index) {
return new MyListIterator(index);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static void main(String[] args) {
MyLinkedList<String> t = new MyLinkedList<String>();
t.add("A");
t.add("B");
t.add("C");
t.add("D");
//t.remove("B");
//t.addFirst("AA");
//t.addLast("BB");
//t.printList();
ListIterator<String> it = t.listIterator(t.size());
while(it.hasPrevious()) {
System.out.println(it.previous()); // D C B A
}
}
}// MyLinkedList end~
ArrayList 底層數組實現的,當實例化一個ArrayList是也至關實例化了一個數組
因此對元素的隨即訪問較快,而增長刪除操做慢
LinkedList 底層實現是一個雙向鏈表,沒一個結點都包含了前一個元素的引用和後一個元素的引用和結點值
因此對元素的隨即訪問很慢,而增刪較快
java 實現鏈表和c實現同樣。 就是指針變成了引用。
鏈表是一種重要的數據結構,在程序設計中佔有很重要的地位。C語言和C++語言中是用指針來實現鏈表結構的,因爲Java語言不提供指針,因此有人認爲在Java語言中不能實現鏈表,其實否則,Java語言比C和C++更容易實現鏈表結構。Java語言中的對象引用其實是一個指針(本文中的指針均爲概念上的意義,而非語言提供的數據類型),因此咱們能夠編寫這樣的類來實現鏈表中的結點。 class Node { Object data; Node next;//指向下一個結點 } 將數據域定義成Object類是由於Object類是廣義超類,任何類對象均可以給其賦值,增長了代碼的通用性。爲了使鏈表能夠被訪問還須要定義一個表頭,表頭必須包含指向第一個結點的指針和指向當前結點的指針。爲了便於在鏈表尾部增長結點,還能夠增長一指向鏈表尾部的指針,另外還能夠用一個域來表示鏈表的大小,當調用者想獲得鏈表的大小時,沒必要遍歷整個鏈表。下圖是這種鏈表的示意圖: 鏈表的數據結構 咱們能夠用類List來實現鏈表結構,用變量Head、Tail、Length、Pointer來實現表頭。存儲當前結點的指針時有必定的技巧,Pointer並不是存儲指向當前結點的指針,而是存儲指向它的前趨結點的指針,當其值爲null時表示當前結點是第一個結點。那麼爲何要這樣作呢?這是由於當刪除當前結點後仍需保證剩下的結點構成鏈表,若是Pointer指向當前結點,則會給操做帶來很大困難。那麼如何獲得當前結點呢,咱們定義了一個方法cursor(),返回值是指向當前結點的指針。類List還定義了一些方法來實現對鏈表的基本操做,經過運用這些基本操做咱們能夠對鏈表進行各類操做。例如reset()方法使第一個結點成爲當前結點。insert(Object d)方法在當前結點前插入一個結點,並使其成爲當前結點。remove()方法刪除當前結點同時返回其內容,並使其後繼結點成爲當前結點,若是刪除的是最後一個結點,則第一個結點變爲當前結點。 鏈表類List的源代碼以下: import java.io.*; public class List { private Node Head=null; private Node Tail=null; private Node Pointer=null; private int Length=0; public void deleteAll() { Head=null; Tail=null; Pointer=null; Length=0; } public void reset() { Pointer=null; } public boolean isEmpty() { return(Length==0); } public boolean isEnd() { if(Length==0) throw new java.lang.NullPointerException(); else if(Length==1) return true; else return(cursor()==Tail); } public Object nextNode() { if(Length==1) throw new java.util.NoSuchElementException(); else if(Length==0) throw new java.lang.NullPointerException(); else { Node temp=cursor(); Pointer=temp; if(temp!=Tail) return(temp.next.data); else throw new java.util.NoSuchElementException(); } } public Object currentNode() { Node temp=cursor(); return temp.data; } public void insert(Object d) { Node e=new Node(d); if(Length==0) { Tail=e; Head=e; } else { Node temp=cursor(); e.next=temp; if(Pointer==null) Head=e; else Pointer.next=e; } Length++; } public int size() { return (Length); } public Object remove() { Object temp; if(Length==0) throw new java.util.NoSuchElementException(); else if(Length==1) { temp=Head.data; deleteAll(); } else { Node cur=cursor(); temp=cur.data; if(cur==Head) Head=cur.next; else if(cur==Tail) { Pointer.next=null; Tail=Pointer; reset(); } else Pointer.next=cur.next; Length--; } return temp; } private Node cursor() { if(Head==null) throw new java.lang.NullPointerException(); else if(Pointer==null) return Head; else return Pointer.next; } public static void main(String[] args) { List a=new List (); for(int i=1;i<=10;i++) a.insert(new Integer(i)); System.out.println(a.currentNode()); while(!a.isEnd()) System.out.println(a.nextNode()); a.reset(); while(!a.isEnd()) { a.remove(); } a.remove(); a.reset(); if(a.isEmpty()) System.out.println("There is no Node in List /n"); System.in.println("You can press return to quit/n"); try { System.in.read(); //確保用戶看清程序運行結果 } catch(IOException e) {} } } class Node { Object data; Node next; Node(Object d) { data=d; next=null; } }