Java經(jīng)典問(wèn)題算法大全
/*【程序1】
題目:古典問(wèn)題:有一對(duì)兔子,從出生后第3個(gè)月起每個(gè)月都生一對(duì)兔子,小兔子長(zhǎng)到第三個(gè)月后每個(gè)月又生一對(duì)兔子,假如兔子都不死,問(wèn)每個(gè)月的兔子總數(shù)為多少?
1.程序分析: 兔子的規(guī)律為數(shù)列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
f = f2;
f2 = f1 + f2;
f1 = f;
System.out.print("第" + i +"個(gè)月的兔子對(duì)數(shù): ");
System.out.println(" " + f2);
}
}
}
/*【程序2】
* 作者 若水飛天
題目:判斷101-200之間有多少個(gè)素?cái)?shù),并輸出所有素?cái)?shù)。
1.程序分析:判斷素?cái)?shù)的方法:用一個(gè)數(shù)分別去除2到sqrt(這個(gè)數(shù)),如果能被整除,
則表明此數(shù)不是素?cái)?shù),反之是素?cái)?shù)。 */
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;//默認(rèn)此數(shù)就素?cái)?shù)
for(int j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
b = false; //此數(shù)不是素?cái)?shù)
break;
}
}
if(b){
count++;
System.out.print(i+" ");
}
}
System.out.println("/n素?cái)?shù)的個(gè)數(shù):"+count);
}
}
/*【程序3】
作者 若水飛天
題目:打印出所有的"水仙花數(shù)(narcissus number)",所謂"水仙花數(shù)"是指一個(gè)三位數(shù),
其各位數(shù)字立方和等于該數(shù)本身。例如:153是一個(gè)"水仙花數(shù)",因?yàn)?53=1的三次方+5的三次方+3的三次方。
1.程序分析:利用for循環(huán)控制100-999個(gè)數(shù),每個(gè)數(shù)分解出個(gè)位,十位,百位。 */
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】
作者 若水飛天
題目:將一個(gè)正整數(shù)分解質(zhì)因數(shù)。例如:輸入90,打印出90=2*3*3*5。
程序分析:對(duì)n進(jìn)行分解質(zhì)因數(shù),應(yīng)先找到一個(gè)最小的質(zhì)數(shù)k,然后按下述步驟完成:
(1)如果這個(gè)質(zhì)數(shù)恰等于n,則說(shuō)明分解質(zhì)因數(shù)的過(guò)程已經(jīng)結(jié)束,打印出即可。
(2)如果n>k,但n能被k整除,則應(yīng)打印出k的值,并用n除以k的商,作為新的正整數(shù)你n,重復(fù)執(zhí)行第一步。
(3)如果n不能被k整除,則用k+1作為k的值,重復(fù)執(zhí)行第一步。 */
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】
作者 若水飛天
題目:利用條件運(yùn)算符的嵌套來(lái)完成此題:學(xué)習(xí)成績(jī)>=90分的同學(xué)用A表示,60-89分之間的用B表示,60分以下的用C表示。
1.程序分析:(a>b)?a:b這是條件運(yùn)算符的基本例子。 */
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】
作者 若水飛天
題目:輸入兩個(gè)正整數(shù)m和n,求其最大公約數(shù)和最小公倍數(shù)。
1.程序分析:利用輾除法。 */
/*
* 在循環(huán)中,只要除數(shù)不等于0,用較大數(shù)除以較小的數(shù),將小的一個(gè)數(shù)作為下一輪循環(huán)的大數(shù),取得的余數(shù)作為下一輪循環(huán)的較小的數(shù),如此循環(huán)直到較小的數(shù)的值為0,返回
* 較大的數(shù),此數(shù)即為最小公約數(shù),最小公倍數(shù)為兩數(shù)之積除以最小公倍數(shù)。
* */
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("最大公約數(shù): " + m);
System.out.println("最小公倍數(shù): " + 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】
作者 若水飛天
題目:輸入一行字符,分別統(tǒng)計(jì)出其中英文字母、空格、數(shù)字和其它字符的個(gè)數(shù)。
1.程序分析:利用while語(yǔ)句,條件為輸入的字符不為 '/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
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("數(shù)字個(gè)數(shù): " + digital);
System.out.println("英文字母?jìng)€(gè)數(shù): " + character);
System.out.println("空格個(gè)數(shù): " + blank);
System.out.println("其他字符個(gè)數(shù):" + other );
}
}
/*【程序8】
作者 若水飛天
題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個(gè)數(shù)字。例如2+22+222+2222+22222(此時(shí)共有5個(gè)數(shù)相加),幾個(gè)數(shù)相加有鍵盤(pán)控制。
*/
/*
* 算法: 定義一個(gè)變量b, 賦初值為0;定義一變量sum, 賦初值為0,
* 進(jìn)入循環(huán)后,將a + b 的值賦給b,將sum + b 的值賦給sum;
* 同時(shí),將a 增加十倍, ++ i; 繼續(xù)循環(huán);
* 循環(huán)結(jié)束后,輸出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】
題目:一個(gè)數(shù)如果恰好等于它的因子之和,這個(gè)數(shù)就稱(chēng)為 "完數(shù) "。例如6=1+2+3.編程 找出1000以?xún)?nèi)的所有完數(shù)。
*/
package cn.com.flywater.FiftyAlgorthm;
public class NinthWanshu {
public static void main(String[] args) {
System.out.println("1到1000的完數(shù)有: ");
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次落地時(shí),共經(jīng)過(guò)多少米?第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】
* 作者 若水飛天
題目:有1、2、3、4個(gè)數(shù)字,能組成多少個(gè)互不相同且無(wú)重復(fù)數(shù)字的三位數(shù)?都是多少?
1.程序分析:可填在百位、十位、個(gè)位的數(shù)字都是1、2、3、4。組成所有的排列后再去 掉不滿足條件的排列。
*/
/*算法:3個(gè)for循環(huán)加一個(gè)if語(yǔ)句;
*
*/
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 + "個(gè)三位數(shù)");
}
}
/*【程序12】
* 作者 若水飛天
題目:企業(yè)發(fā)放的獎(jiǎng)金根據(jù)利潤(rùn)提成。利潤(rùn)(I)低于或等于10萬(wàn)元時(shí),獎(jiǎng)金可提10%;
利潤(rùn)高于10萬(wàn)元,低于20萬(wàn)元時(shí),低于10萬(wàn)元的部分按10%提成,高于10萬(wàn)元的部分,
可可提成7.5%;20萬(wàn)到40萬(wàn)之間時(shí),高于20萬(wàn)元的部分,
可提成5%;40萬(wàn)到60萬(wàn)之間時(shí)高于40萬(wàn)元的部分,可提成3%;
60萬(wàn)到100萬(wàn)之間時(shí),高于60萬(wàn)元的部分,可提成1.5%,高于100萬(wàn)元時(shí),超過(guò)100萬(wàn)元的部分按1%提成,
從鍵盤(pán)輸入當(dāng)月利潤(rùn)I,求應(yīng)發(fā)放獎(jiǎng)金總數(shù)?
1.程序分析:請(qǐng)利用數(shù)軸來(lái)分界,定位。注意定義時(shí)需把獎(jiǎng)金定義成長(zhǎng)整型。
*/
/*注意: 要精確到小數(shù)點(diǎn)后多少位,用 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("輸入的利潤(rùn)是" + profit + "萬(wàn)");
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("應(yīng)該提取的獎(jiǎng)金是 " + df.format(award) + "萬(wàn)");
}
}
/*【程序13】
* 作者 若水飛天
題目:一個(gè)整數(shù),它加上100后是一個(gè)完全平方數(shù),再加上168又是一個(gè)完全平方數(shù),請(qǐng)問(wèn)該數(shù)是多少?
1.程序分析:在10萬(wàn)以?xún)?nèi)判斷,先將該數(shù)加上100后再開(kāi)方,再將該數(shù)加上268后再開(kāi)方,
如果開(kāi)方后的結(jié)果滿足如下條件,即是結(jié)果。請(qǐng)看具體分析:
*/
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是一個(gè)完全平方數(shù),再加168又是一個(gè)完全平方數(shù)");
}
}
}
}
}
*【程序14】
* 作者 若水飛天
題目:輸入某年某月某日,判斷這一天是這一年的第幾天?
1.程序分析:以3月5日為例,應(yīng)該先把前兩個(gè)月的加起來(lái),
然后再加上5天即本年的第幾天,特殊情況,閏年且輸入月份大于3時(shí)需考慮多加一天。
*/
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
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】
* 作者?? 若水飛天
題目:輸入三個(gè)整數(shù)x,y,z,請(qǐng)把這三個(gè)數(shù)由小到大輸出。
1.程序分析:我們想辦法把最小的數(shù)放到x上,先將x與y進(jìn)行比較,如果x> y則將x與y的值進(jìn)行交換,然后再用x與z進(jìn)行比較,如果x> z則將x與z的值進(jìn)行交換,這樣能使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);//方法調(diào)用不能通過(guò)改變形參的值來(lái)改變實(shí)參的值
//?? fnc.compare(b, c);// 這種做法是錯(cuò)的
//?? fnc.compare(a, c);
//System.out.println("result:" + a +" " + b + " " + c);// 沒(méi)有改變
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) {//此方法沒(méi)用
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】
//作者 若水飛天
//題目:猴子吃桃問(wèn)題:猴子第一天摘下若干個(gè)桃子,當(dāng)即吃了一半,還不癮,
//又多吃了一個(gè) 第二天早上又將剩下的桃子吃掉一半,又多吃了一個(gè)。
//以后每天早上都吃了前一天剩下 的一半零一個(gè)。到第10天早上想再吃時(shí),
//見(jiàn)只剩下一個(gè)桃子了。求第一天共摘了多少。
//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 + " 個(gè)桃子");
}
}
/*【程序18】
* 作者 若水飛天
題目:兩個(gè)乒乓球隊(duì)進(jìn)行比賽,各出三人。甲隊(duì)為a,b,c三人,乙隊(duì)為x,y,z三人。
已抽簽決定比賽名單。有人向隊(duì)員打聽(tīng)比賽的名單。a說(shuō)他不和x比,c說(shuō)他不和x,z比,請(qǐng)編程序找出三隊(duì)賽手的名單。
*/
/*
* 這個(gè)程序?qū)懙煤懿缓茫侵澜Y(jié)果后拼湊起來(lái)的,還不如直接寫(xiě)輸出語(yǔ)句加上結(jié)果來(lái)的好。
*/
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.程序分析:先把圖形分成兩部分來(lái)看待,前四行一個(gè)規(guī)律,后三行一個(gè)規(guī)律,利用雙重 for循環(huán),
第一層控制行,第二層控制列。
*/
/*上半部分循環(huán)變量的控制方法是
* for(int i=0; i<(HEIGHT+1) / 2; i++) {
for(int j=1; j
for(int k=1; k<(i+1)*2; k++) {
下半部分循環(huán)變量的控制方法是
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
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();
}
}
}
上半部分第二重循環(huán)應(yīng)改為:??? for(int j=0; j
上半部分第三重循環(huán)應(yīng)改為:??? for(int k=1; k<=WIDTH-2*i; k++)
/*【程序20】
* 作者 若水飛天
題目:有一分?jǐn)?shù)序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個(gè)數(shù)列的前20項(xiàng)之和。
1.程序分析:請(qǐng)抓住分子與分母的變化規(guī)律。
*/
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個(gè)人坐在一起,問(wèn)第五個(gè)人多少歲?他說(shuō)比第4個(gè)人大2歲。
問(wèn)第4個(gè)人歲數(shù),他說(shuō)比第3個(gè)人大2歲。問(wèn)第三個(gè)人,又說(shuō)比第2人大兩歲。
問(wèn)第2個(gè)人,說(shuō)比第一個(gè)人大兩歲。最后問(wèn)第一個(gè)人,他說(shuō)是10歲。請(qǐng)問(wèn)第五個(gè)人多大?
1.程序分析:利用遞歸的方法,遞歸分為回推和遞推兩個(gè)階段。
要想知道第五個(gè)人歲數(shù),需知道第四人的歲數(shù),依次類(lèi)推,推到第一人(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】
* 作者 若水飛天
題目:給一個(gè)不多于5位的正整數(shù),
要求:一、求它是幾位數(shù),二、逆序打印出各位數(shù)字。
說(shuō)明: 這個(gè)算法實(shí)現(xiàn)雖然實(shí)現(xiàn)了這個(gè)功能,但不健壯,當(dāng)輸入字符是,會(huì)出現(xiàn)異常。
*/
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 + "是一位數(shù)");
System.out.println("按逆序輸出是" + '/n' + a);
} else if(a >= 10 && a <= 99) {
System.out.println(a + "是二位數(shù)");
System.out.println("按逆序輸出是" );
tn.converse(a);
} else if(a >= 100 && a <= 999) {
System.out.println(a + "是三位數(shù)");
System.out.println("按逆序輸出是" );
tn.converse(a);
} else if(a >= 1000 && a <= 9999) {
System.out.println(a + "是四位數(shù)");
System.out.println("按逆序輸出是" );
tn.converse(a);
} else if(a >= 10000 && a <= 99999) {
System.out.println(a + "是五位數(shù)");
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]);
}
}
}
這個(gè)算法實(shí)在太土了,也許只有我若水飛天才會(huì)這樣寫(xiě),
下面寫(xiě)一個(gè)優(yōu)雅一點(diǎn)的
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 + “位數(shù)”);
for(int i=ch.length-1; i>=0; i--) {
System.out.print(ch[i]);
}
}
}
/*【程序25】
* 作者 若水飛天
題目:一個(gè)5位數(shù),判斷它是不是回文數(shù)。即12321是回文數(shù),個(gè)位與萬(wàn)位相同,十位與千位相同。
**/
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!");
}
}
}
這個(gè)更好,不限位數(shù)
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("請(qǐng)輸入一個(gè)正整數(shù):");
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
if(ch[i]!=ch[j-i-1]){is=false;}
}
if(is==true){System.out.println("這是一個(gè)回文數(shù)");}
else {System.out.println("這不是一個(gè)回文數(shù)");}
}
/*【程序26】
* 作者?? 若水飛天
題目:請(qǐng)輸入星期幾的第一個(gè)字母來(lái)判斷一下是星期幾,
如果第一個(gè)字母一樣,則繼續(xù) 判斷第二個(gè)字母。
1.程序分析:用情況語(yǔ)句比較好,如果第一個(gè)字母一樣,
則判斷用情況語(yǔ)句或if語(yǔ)句判斷第二個(gè)字母。
此程序雖然實(shí)現(xiàn)了基本功能,但必須嚴(yán)格按照題目的要求輸入,否則程序無(wú)法執(zhí)行
**/
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之內(nèi)的素?cái)?shù)
1.程序分析:判斷素?cái)?shù)的方法:用一個(gè)數(shù)分別去除2到sqrt(這個(gè)數(shù)),
如果能被整除, 則表明此數(shù)不是素?cái)?shù),反之是素?cái)?shù)。
**/
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】
* 作者 若水飛天
題目:對(duì)10個(gè)數(shù)進(jìn)行排序
1.程序分析:可以利用選擇法,即從后9個(gè)比較過(guò)程中,
選擇一個(gè)最小的與第一個(gè)元素交換, 下次類(lèi)推,
即用第二個(gè)元素與后8個(gè)進(jìn)行比較,并進(jìn)行交換。
**/
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】
* 作者??? 若水飛天
* 按程序分析,好像只是求主對(duì)角線的和
題目:求一個(gè)3*3矩陣對(duì)角線元素之和
1.程序分析:利用雙重for循環(huán)控制輸入二維數(shù)組,再將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("對(duì)角線和是 " + sum);
}
}
/*【程序30】
* 作者 若水飛天
題目:有一個(gè)已經(jīng)排好序的數(shù)組?,F(xiàn)輸入一個(gè)數(shù),要求按原來(lái)的規(guī)律將它插入數(shù)組中。
1. 程序分析:首先判斷此數(shù)是否大于最后一個(gè)數(shù),
然后再考慮插入中間的數(shù)的情況,插入后此元素之后的數(shù),依次后移一個(gè)位置。
**/
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();
/*
* 定義兩個(gè)數(shù)組a,b,一個(gè)a的長(zhǎng)度比另一個(gè)b大1, a看做是
* 已經(jīng)排好序的。
* 接下來(lái)的過(guò)程是
* 1: 如果num 比最后一個(gè)數(shù)大,把num賦值給數(shù)組b的最后一個(gè)數(shù)
*??? 再按順序把a(bǔ) 的每個(gè)元素賦給b
* 2: 否則(num 不比a 的最后一個(gè)數(shù)大),
*???? 如果a 的元素比num 小,則將這些元素按順序賦給b
*???? 將num 賦給比num大的b數(shù)組的元素,
*???? 跳出第一個(gè)for循環(huán)。
* 3: 定義一個(gè)循環(huán)控制變量,從num傳給數(shù)組后num的下標(biāo)值加一開(kāi)始;
*??? 直到b的結(jié)尾,將剩下的a 的值賦給b,賦值的過(guò)程是b[j] = a[i-1];
*
*/
if(num >= a[a.length-1]) {
b[b.length-1] = num;
for(i=0; i
b[i] = a[i];
}
} else {
for(i=0; i
if(num >= a[i]) {
b[i] = a[i];
} else {
b[i] = num;
break;
}
}
for(int j=i+1; 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】
* 作者?? 若水飛天
題目:取一個(gè)整數(shù)a從右端開(kāi)始的4~7位。
程序分析:可以這樣考慮:
(1)先使a右移4位。
(2)設(shè)置一個(gè)低4位全為1,其余全為0的數(shù)。可用~(~0 < <4)
(3)將上面二者進(jìn)行&運(yùn)算。
**/
/*這個(gè)題我不會(huì)做,如有高手路過(guò),還望指點(diǎn)
*
*/
package cn.com.flywater.FiftyAlgorthm;
public class Thirty_secondFS {
public static void main(String[] args) {
}
}
我沒(méi)有用提示的方法,采用了字串截取。
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean is =true;
System.out.print("請(qǐng)輸入一個(gè)7位以上的正整數(shù):");
long a = s.nextLong();
String ss = Long.toString(a);
char[] ch = ss.toCharArray();
int j=ch.length;
if (j<7){System.out.println("輸入錯(cuò)誤!");}
else {
System.out.println("截取從右端開(kāi)始的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
*/
/*
* 網(wǎng)上千篇一律是這種寫(xiě)法,我也沒(méi)有什么創(chuàng)新,
* a[i][j]=a[i-1][j]+a[i-1][j-1] 就是這個(gè)程序的核心
* 定義的是二維數(shù)組,為了使輸出的結(jié)果看起來(lái)漂亮一點(diǎn)
* 可以用for(int k=0; k<2*(10-i)-1; k++)控制輸出的空格
* 這個(gè)循環(huán)是在控制行數(shù)的循環(huán)里面,控制列數(shù)的循環(huán)外面。
* 記得在輸出菱形時(shí)為了控制下半部分的輸出,在下拼命的寫(xiě)出
* 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
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個(gè)數(shù)a,b,c,按大小順序輸出。
1.程序分析:利用指針?lè)椒ā?/p>
*/
/*
* 可惜,Java好像沒(méi)有指針
*/
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】
* 作者 若水飛天
題目:輸入數(shù)組,最大的與第一個(gè)元素交換,最小的與最后一個(gè)元素交換,輸出數(shù)組。
**/
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
a[i] = s.nextInt();
System.out.print(a[i] + " ");
}
int max =a[0], min = a[0];
for(int i=0; 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
System.out.print(a[i] + " ");
}
}
}
/*【程序36】
* 作者??? 若水飛天
題目:有n個(gè)整數(shù),使其前面各數(shù)順序向后移m個(gè)位置,最后m個(gè)數(shù)變成最前面的m個(gè)數(shù)
**/
/*
* 這個(gè)題不知道有什么好辦法,比較直接方法的是把這個(gè)數(shù)組分成兩個(gè)數(shù)組,
* 再將兩個(gè)數(shù)組合起來(lái),但如果不控制好數(shù)組的下標(biāo),就會(huì)帶來(lái)很多麻煩。
*/
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[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
b[i] = a[i];
}
for(int i=m,j=0; i
c[j] = a[i];
}
for(int i=0; i
a[i] = c[i];
}
for(int i=m,j=0; i
a[i] = b[j];
}
for(int i=0; i
System.out.print(a[i] + " ");
}
}
}
/*【程序37】
* 作者 若水飛天
題目:有n個(gè)人圍成一圈,順序排號(hào)。從第一個(gè)人開(kāi)始報(bào)數(shù)(從1到3報(bào)數(shù)),
凡報(bào)到3的人退出圈子,問(wèn)最后留下的是原來(lái)第幾號(hào)的那位。
**/
/*
* 這個(gè)程序是完全抄別人的
*/
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[i] = true;//下標(biāo)為T(mén)RUE時(shí)說(shuō)明還在圈里
}
int leftCount = n;
int countNum = 0;
int index = 0;
while(leftCount > 1) {
if(arr[index] == true) {//當(dāng)在圈里時(shí)
countNum ++; //報(bào)數(shù)遞加
if(countNum == 3) {//報(bào)道3時(shí)
countNum =0;//從零開(kāi)始繼續(xù)報(bào)數(shù)
arr[index] = false;//此人退出圈子
leftCount --;//剩余人數(shù)減一
}
}
index ++;//每報(bào)一次數(shù),下標(biāo)加一
if(index == n) {//是循環(huán)數(shù)數(shù),當(dāng)下標(biāo)大于n時(shí),說(shuō)明已經(jīng)數(shù)了一圈,
index = 0;//將下標(biāo)設(shè)為零重新開(kāi)始。
}
}
for(int i=0; i
if(arr[i] == true) {
System.out.println(i);
}
}
}
}
/*【程序38】
* 作者 若水飛天
題目:寫(xiě)一個(gè)函數(shù),求一個(gè)字符串的長(zhǎng)度,在main函數(shù)中輸入字符串,并輸出其長(zhǎng)度。
*/
package cn.com.flywater.FiftyAlgorthm;
public class Thirty_eighthStringLength {
public static void main(String[] args) {
String s = "jdfifdfhfhuififffdfggee";
System.out.print("字符串的長(zhǎng)度是:");
System.out.println(s.length());
}
}
*【程序39】
* 作者??? 若水飛天
題目:編寫(xiě)一個(gè)函數(shù),輸入n為偶數(shù)時(shí),調(diào)用函數(shù)求1/2+1/4+...+1/n,
當(dāng)輸入n為奇數(shù)時(shí),調(diào)用函數(shù)1/1+1/3+...+1/n(利用指針函數(shù))
**/
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
for(int j=i+1; j
if(s[i].compareToIgnoreCase(s[j]) > 0) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}*/
for(int i=0; i
for(int j=i+1; j
if(compare(s[i], s[j]) == false) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for(int i=0; i
System.out.println(s[i]);
}
}
static boolean compare(String s1, String s2) {
boolean result = true;
for(int i=0; i
if(s1.charAt(i) > s2.charAt(i)) {
result = false;
break;
} else if(s1.charAt(i)
result = true;
break;
} else {
if(s1.length() < s2.length()) {
result = true;
} else {
result = false;
}
}
}
return result;
}
}
LinkedList類(lèi)里面較重要的方法就是"addBefore(){}"和"private void remove(DNode curr){}"
很多方法都與它倆有關(guān)系!!
下面的代碼是個(gè)雙向循環(huán)鏈表,在LinkedList里抄的...
package LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class MyLinkedList {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private DNode header;
private int listSize;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public MyLinkedList() {
header = new DNode();
listSize = 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private static class DNode {
T nodeValue;
DNode prev;
DNode 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 addBefore(DNode curr, T item) {
DNode newNode, prevNode;
newNode = new DNode(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 curr) {
if(curr.next == curr) return;
DNode prevNode = curr.prev, nextNode = curr.next;
prevNode.next = nextNode;
nextNode.prev= prevNode;
}
public boolean remove(Object o) {
for(DNode 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 p = header.next; p != header; p = p.next)
System.out.println(p.nodeValue);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class MyIterator implements Iterator {
public DNode nextNode = header.next;
public DNode 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 {
private int nextIndex;
MyListIterator(int index) {
if(index < 0 || index > listSize)
throw new IndexOutOfBoundsException("");
//如果index小于listSize/2,就從表頭開(kāi)始查找定位,否則就從表尾開(kāi)始查找定位
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 iterator() {
return new MyIterator();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public ListIterator listIterator(int index) {
return new MyListIterator(index);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static void main(String[] args) {
MyLinkedList t = new MyLinkedList();
t.add("A");
t.add("B");
t.add("C");
t.add("D");
//t.remove("B");
//t.addFirst("AA");
//t.addLast("BB");
//t.printList();
ListIterator it = t.listIterator(t.size());
while(it.hasPrevious()) {
System.out.println(it.previous()); // D C B A
}
}
}// MyLinkedList end~
ArrayList 底層數(shù)組實(shí)現(xiàn)的,當(dāng)實(shí)例化一個(gè)ArrayList是也相當(dāng)實(shí)例化了一個(gè)數(shù)組
所以對(duì)元素的隨即訪問(wèn)較快,而增加刪除操作慢
LinkedList 底層實(shí)現(xiàn)是一個(gè)雙向鏈表,沒(méi)一個(gè)結(jié)點(diǎn)都包含了前一個(gè)元素的引用和后一個(gè)元素的引用和結(jié)點(diǎn)值
所以對(duì)元素的隨即訪問(wèn)很慢,而增刪較快
java 實(shí)現(xiàn)鏈表和c實(shí)現(xiàn)一樣。 就是指針變成了引用。
【參考資料】JAVA的鏈表(2009-05-11 01:35:49)標(biāo)簽:java 鏈表?? 分類(lèi):學(xué)習(xí)資料
又是個(gè)不錯(cuò)的地方:http://blog.sina.com.cn/s/articlelist_1282789430_0_1.html
鏈表是一種重要的數(shù)據(jù)結(jié)構(gòu),在程序設(shè)計(jì)中占有很重要的地位。C語(yǔ)言和C++語(yǔ)言中是用指針來(lái)實(shí)現(xiàn)鏈表結(jié)構(gòu)的,由于Java語(yǔ)言不提供指針,所以有人認(rèn)為在Java語(yǔ)言中不能實(shí)現(xiàn)鏈表,其實(shí)不然,Java語(yǔ)言比C和C++更容易實(shí)現(xiàn)鏈表結(jié)構(gòu)。Java語(yǔ)言中的對(duì)象引用實(shí)際上是一個(gè)指針(本文中的指針均為概念上的意義,而非語(yǔ)言提供的數(shù)據(jù)類(lèi)型),所以我們可以編寫(xiě)這樣的類(lèi)來(lái)實(shí)現(xiàn)鏈表中的結(jié)點(diǎn)。
class Node
{
Object data;
Node next;//指向下一個(gè)結(jié)點(diǎn)
}
將數(shù)據(jù)域定義成Object類(lèi)是因?yàn)镺bject類(lèi)是廣義超類(lèi),任何類(lèi)對(duì)象都可以給其賦值,增加了代碼的通用性。為了使鏈表可以被訪問(wèn)還需要定義一個(gè)表頭,表頭必須包含指向第一個(gè)結(jié)點(diǎn)的指針和指向當(dāng)前結(jié)點(diǎn)的指針。為了便于在鏈表尾部增加結(jié)點(diǎn),還可以增加一指向鏈表尾部的指針,另外還可以用一個(gè)域來(lái)表示鏈表的大小,當(dāng)調(diào)用者想得到鏈表的大小時(shí),不必遍歷整個(gè)鏈表。下圖是這種鏈表的示意圖:
鏈表的數(shù)據(jù)結(jié)構(gòu)
我們可以用類(lèi)List來(lái)實(shí)現(xiàn)鏈表結(jié)構(gòu),用變量Head、Tail、Length、Pointer來(lái)實(shí)現(xiàn)表頭。存儲(chǔ)當(dāng)前結(jié)點(diǎn)的指針時(shí)有一定的技巧,Pointer并非存儲(chǔ)指向當(dāng)前結(jié)點(diǎn)的指針,而是存儲(chǔ)指向它的前趨結(jié)點(diǎn)的指針,當(dāng)其值為null時(shí)表示當(dāng)前結(jié)點(diǎn)是第一個(gè)結(jié)點(diǎn)。那么為什么要這樣做呢?這是因?yàn)楫?dāng)刪除當(dāng)前結(jié)點(diǎn)后仍需保證剩下的結(jié)點(diǎn)構(gòu)成鏈表,如果Pointer指向當(dāng)前結(jié)點(diǎn),則會(huì)給操作帶來(lái)很大困難。那么如何得到當(dāng)前結(jié)點(diǎn)呢,我們定義了一個(gè)方法cursor(),返回值是指向當(dāng)前結(jié)點(diǎn)的指針。類(lèi)List還定義了一些方法來(lái)實(shí)現(xiàn)對(duì)鏈表的基本操作,通過(guò)運(yùn)用這些基本操作我們可以對(duì)鏈表進(jìn)行各種操作。例如reset()方法使第一個(gè)結(jié)點(diǎn)成為當(dāng)前結(jié)點(diǎn)。insert(Object d)方法在當(dāng)前結(jié)點(diǎn)前插入一個(gè)結(jié)點(diǎn),并使其成為當(dāng)前結(jié)點(diǎn)。remove()方法刪除當(dāng)前結(jié)點(diǎn)同時(shí)返回其內(nèi)容,并使其后繼結(jié)點(diǎn)成為當(dāng)前結(jié)點(diǎn),如果刪除的是最后一個(gè)結(jié)點(diǎn),則第一個(gè)結(jié)點(diǎn)變?yōu)楫?dāng)前結(jié)點(diǎn)。
鏈表類(lèi)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();
//確保用戶(hù)看清程序運(yùn)行結(jié)果
}
catch(IOException e)
{}
}
}
class Node
{
Object data;
Node next;
Node(Object d)
{
data=d;
next=null;
}
}