package javahomework; import javax.swing.JOptionPane; class postfix { private char stack[], z[]; private int pri[] = { 0, 1, 1, 2, 2, 3 }; private char oper[] = { '(', '+', '-', '*', '/', '^' }; private int top, n, a; private String postfix = ""; private char x[], y; public postfix() { n = 50; top = 0; a = 0; stack = new char[n]; z = new char[n]; } public String infix_to_postfix(String infix) { int i = 0, j = infix.length(); x = infix.toCharArray(); for (i = 0; i < j; i++) { switch (x[i]) { case '(': push(x[i]); break; case ')': y = pop(); while (!empty() && y != '(') { z[a++] = y; y = pop(); } break; case '+': case '-': case '*': case '/': case '^': y = top(); while (pre(y) >= pre(x[i])) { z[a++] = pop(); y = top(); } push(x[i]); break; default: z[a++] = x[i]; } } while (!empty()) { z[a++] = pop(); } for (i = 0; i <= a - 2; i++) { postfix += z[i]; postfix += " "; } return postfix; } private boolean empty() { return (top < 0) ? true : false; } private boolean full() { return (top >= n - 1) ? true : false; } private void push(char sta) { stack[++top] = sta; } private char pop() { return stack[top--]; } private char top() { return stack[top]; } private int pre(char op) { for (int i = 0; i < 6; i++) if (oper[i] == op) return pri[i]; return -1; } private void check(char x, char y) { y = top(); while (pre(y) >= pre(x)) { postfix += pop(); y = top(); } push(x); } } public class HW18 { public static void main(String arg[]) { String input = JOptionPane.showInputDialog(null, "Please input string (ex.1+2-3)"); postfix p = new postfix(); JOptionPane.showMessageDialog(null, String.valueOf(p.infix_to_postfix(input))); } }
2008年8月30日 星期六
中置轉成後置
code
2008年8月29日 星期五
簡易計算機
只計算一次 A+B 或 A-B
code
code
package javahomework; import javax.swing.JOptionPane; public class HW17 { static int toNumber(char array[], int begin, int end) { String temp = ""; for (int i = begin; i < end; i++) temp += array[i]; return Integer.parseInt(temp); } static long sum_number(String input) { int index = 0; long sum = 0; char a[] = input.toCharArray(); for (int i = 0; i < a.length; i++) { switch (a[i]) { case '+': // A+B sum += toNumber(a, 0, i) + toNumber(a, i + 1, a.length); break; case '-': // A-B sum += toNumber(a, 0, i) - toNumber(a, i + 1, a.length); break; } index++; } return sum; } public static void main(String args[]) { String input = JOptionPane.showInputDialog(null, "Please input 1+2 or 1-2"); JOptionPane.showMessageDialog(null, String.valueOf(sum_number(input))); } }
字串大小寫轉換
code
package javahomework; import javax.swing.JOptionPane; import java.util.StringTokenizer; public class HW16 { public static void main(String args[]) { String input = JOptionPane.showInputDialog(null, ""); StringTokenizer st = new StringTokenizer(input); String out = ""; while (st.hasMoreTokens()) { String tmp = st.nextToken(); StringBuffer buf1 = new StringBuffer(tmp); StringBuffer buf2 = new StringBuffer(tmp); out = out + buf1.toString().toLowerCase() + buf2.toString().toUpperCase() + " "; } JOptionPane.showMessageDialog(null, out); } }
定義一個點->圓->圓錐體->雙圓錐體
code
package javahomework; public class HW15 { class Point { private double x, y; public Point() { x = 1.0; y = 1.0; } public Point(double n1, double n2) { x = n1; y = n2; } public double getX() { return x; } public double getY() { return y; } } class Circle{ private double r; private Point p; public double pi = 3.1415926; Circle() { r = 1.0; } public double findArea() { return r * r * pi; } public double findlength() { return r * pi * 2; } public void set(double n,Point p) { r = n; } public double get_r() { return r; } public Point get_Point(){ return p; } public void set_Point(Point p){ this.p = p; } } class Cone extends Circle { private double r = super.get_r(); private double h; Cone() { h = 1.0; } Cone(double n1, double n2) { r = n1; h = n2; } public void set(double n1, double n2) { r = n1; h = n2; } public double getR() { return r; } public double getH() { return h; } public double findVolume() { return (pi * r * r * h) / 3; } public double findFaceArea() { return (Math.pow((r * r) + (h * h), 0.5)) * 2 * pi; } } class DouleCone extends Cone { private double r = super.getR(); private double h = super.getH(); public double findDoublejVolume() { return super.findVolume() * 2; } public double findDoubleH() { return h * 2; } public double findDoubleVolume() { return super.findVolume() * 2; } public double findDoubleFaceArea1() {// 漏斗 return super.findFaceArea() * 2; } public double findDoubleFaceArea2() {// 兩邊尖 return (super.findFaceArea() * 2) - (r * r * pi) * 2; } } }
定義一個父矩形,子長方體並繼承
code
package javahomework; public class HW14 { class Rectangle { private double length1, length2; public Rectangle() { length1 = 1.0; length2 = 1.0; } public Rectangle(double n) { length1 = n; length2 = n; } public Rectangle(double n1, double n2) { length1 = n1; length2 = n2; } public void set(double n1, double n2) { length1 = n1; length2 = n2; } public double getL1() { return length1; } public double getL2() { return length2; } public double findArea() { return length1 * length2; } public double find4Length() { return (length1 + length2) * 2; } } class AdRectangle extends Rectangle { private double hight; AdRectangle() { hight = 1.0; } AdRectangle(double n1, double n2, double n3) { super(n1, n2); hight = n3; } public void set(double n1, double n2, double n3) { super.set(n1, n2); hight = n3; } public double findVolume() { return super.findArea() * hight; } public double findArea() { return super.getL1() * super.getL2(); } public double findFaceArea() { return super.findArea() * 2 + super.getL1() * hight * 2 + super.getL2() * hight * 2; } } }
計算1+1/1+1/2!+1/3!+1/4!
code
package javahomework; import javax.swing.JOptionPane; public class HW13 { static double Count(int n) { if (n == 0 || n == 1) return 1; else return n * (Count(n - 1)); } public static void main(String arg[]) { int input; float ans = 0; input = Integer.parseInt(JOptionPane.showInputDialog(null, "How much do you want to count?")); for (int i = 0; i < input; i++) ans += 1 / (Count(i)); ans -= (ans % 0.000001); JOptionPane.showMessageDialog(null, "Number is " + ans); } }
算出PI
注意:要計算很久,會把CPU資源吃光光
code
code
package javahomework; import javax.swing.JOptionPane; public class HW12 { public static void main(String arg[]) { double p = 0, input = 1e10; int x = -1; for (double i = 0; i < input; i++) { x *= -1; // 4x(1-1/3+1/5-1/7+1/9...) p += 4 * ((1 / (2 * i + 1)) * x); } p -= p % 0.0000000001; JOptionPane.showMessageDialog(null, "PI is " + p); } }
計算產生第幾個新的類別
技巧:設定變數為static
code
code
package javahomework; import javax.swing.JOptionPane; class TestC { static int count = 0; public static TestC getInstance() { TestC x = new TestC(); count++; return x; } public static String get_count() { return String.valueOf(count); } } public class HW11 { public static void main(String args[]) { TestC c1 = TestC.getInstance(); TestC c2 = TestC.getInstance(); TestC c3 = TestC.getInstance(); JOptionPane.showMessageDialog(null, TestC.get_count()); } }
用類別寫陣列堆疊
code
package javahomework; import javax.swing.JOptionPane; class Queue { int Q[], front, rear, newrear, MaxSize; String screen = ""; public Queue() { MaxSize = 5; Q = new int[MaxSize]; front = rear = -1; } public void add(int x) { if (isfull()) JSM("Queue is full"); else { Q[rear = newrear] = x; JSM("Add " + x); } } public void delete() { if (isempty()) JSM("Queuq is empty"); else front = (front + 1) % MaxSize; JSM("Delete " + Q[front]); } public boolean isempty() { if (rear == front) return true; else return false; } public boolean isfull() { newrear = (rear + 1) % MaxSize; if (front == newrear) return true; else return false; } private void JSM(String messeng) { JOptionPane.showMessageDialog(null, messeng); } public void dump() { if (isempty()) JSM("Queuq is empty"); else for (int i = 0; i < Q.length; i++) screen = screen + Q[i] + " "; JSM(screen); } } public class HW10 { public static void main(String args[]) { Queue q1 = new Queue(); q1.add(1); q1.add(2); q1.delete(); q1.add(3); q1.add(4); q1.delete(); q1.add(5); q1.add(6); q1.add(7); q1.dump(); } }
利用類別特性定義一個圓錐體,並且可以算出體積、表面積
code
package javahomework; public class HW09 { public static void main(String args[]) { Cone r1 = new Cone(); Cone r2 = new Cone(10.0); Cone r3 = new Cone(15.0, 20.0); System.out.println("Volume is " + r1.volume() + " FaceArea is " + r1.facearea()); System.out.println("Volume is " + r2.volume() + " FaceArea is " + r2.facearea()); System.out.println("Volume is " + r3.volume() + " FaceArea is " + r3.facearea()); } } class Cone { double r, h; double pi = 3.14; Cone(double a, double b) { r = a; h = b; } Cone() { r = 1.0; h = 1.0; } Cone(double a) { r = a; h = a; } double volume() { return (pi * r * r * h) / 3; } double facearea() { return (Math.pow((r * r) + (h * h), 0.5)) * 2 * pi; } }
利用亂數產生兩個二維陣列A,B計算出C=A*B
code
package javahomework; public class HW08 { public static void main(String arg[]) { int a[][] = new int[2][2]; int b[][] = new int[2][2]; int c[][] = new int[2][2]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = (int) (Math.random() * 10); for (int i = 0; i < b.length; i++) for (int j = 0; j < b[i].length; j++) b[i][j] = (int) (Math.random() * 10); for (int i = 0; i < a.length; i++) for (int j = 0; j < b[i].length; j++) for (int k = 0; k < b[j].length; k++) c[i][j] = c[i][j] + a[i][k] * b[k][j]; for (int i = 0; i < c.length; i++) { for (int j = 0; j < c[i].length; j++) System.out.print(c[i][j] + " "); System.out.print("\n"); } } }
輸入一個一級陣列,利用氣泡排序法排序
code
package javahomework; import javax.swing.JOptionPane; public class HW07 { public static void main(String args[]) { int a[] = new int[10]; String screen = "Sort "; for (int x = 0; x < a.length; x++) a[x] = Integer.parseInt(JOptionPane.showInputDialog(null, "Input Number")); bubblesort(a); for (int y = 0; y < a.length; y++) screen = screen + a[y] + " "; JOptionPane.showMessageDialog(null, screen); } public static void bubblesort(int n[]) { for (int i = 0; i < n.length - 1; i++) for (int j = 0; j < n.length - 1; j++) if (n[j + 1] > n[j]) { int tmp = n[j]; n[j] = n[j + 1]; n[j + 1] = tmp; } } }
輸入一個數,計算其檢查碼
code
package javahomework; import javax.swing.JOptionPane; public class HW06 { public static void main(String args[]) { int input; input = Integer.parseInt(JOptionPane.showInputDialog(null, "")); JOptionPane.showMessageDialog(null, "Check Number is " + Number(input)); } static int Number(int n) { return ((ADD(n) % ADD2(n)) % 10); } static int ADD(int n) { if (n < 10) return (n * n); else return (ADD(n / 10) + ADD(n % 10)); } static int ADD2(int n) { if (n < 10) return n; else return (ADD2(n / 10) + ADD2(n % 10)); } }
找出1~2000中所有的Perfect number
Perfect number 是指某一個數,其因數相加會等於其數
code
code
package javahomework; import javax.swing.JOptionPane; public class HW05 { public static void main(String args[]) { String Screen = "The PerfectNumber is "; for (int j = 4; j < 2000; j++) { if (AD(j) == j) Screen = Screen + j + ","; } JOptionPane.showMessageDialog(null, Screen); } static int AD(int n) { int ans = 1; for (int i = 2; i < n; i++) { if (n % i == 0) ans = ans + i; } return ans; } }
輸入一個數,算出所有數的總和
把輸入的數字一直除以10,剩下10以下的餘數再相加即可
code
code
package javahomework; import javax.swing.JOptionPane; public class HW04 { public static void main(String args[]) { int input; input = Integer.parseInt(JOptionPane.showInputDialog(null,"Input Number")); JOptionPane.showMessageDialog(null,"The sum of "+input+" is "+ADD(input)); } static int ADD(int n) { if (n<10) return n; else return (ADD(n/10)+ADD(n%10)); } }
2008年8月27日 星期三
2008年8月19日 星期二
求出第一個大於100000的費式數列是第幾項
用遞迴的寫法
/** * FIB use recursive * * @param big_number * @return big than big_number is */ public static int fib_slow(long big_number) { long f = 1; int ans = 0; for (long i = 0; f < big_number; i++) { f = fib(i); ans++; } return ans; } public static long fib(long n) { if (n == 0 || n == 1) return n; else return (fib(n - 2) + fib(n - 1)); }用單一迴圈的寫法,所花的時候只有O(n)
/** * FIB not use recursive * * @param number * @return big than big_number is */ public static int fib_quick(long number) { long a, b, c; /* A[0]=0,A[1]=1 has been count in first time, so ans=2*/ int ans = 2; a = 0; b = 1; c = a + b; while (c < number) { /* A[n+2]=A[n]+A[n+1]; */ c = a + b; /* next ...., let A be a=A[n+1],b=A[n+2] */ a = b; b = c; ans++; } return ans; }code
最大公因數 Greatest common divisor
code
package javahomework; import javax.swing.JOptionPane; public class HW01 { /** * Main * * @param args */ public static void main(String args[]) { int number1 = Integer.parseInt(JOptionPane.showInputDialog(null, "Please Input Number1 ")); int number2 = Integer.parseInt(JOptionPane.showInputDialog(null, "Please Input Number2 ")); JOptionPane.showMessageDialog(null, "GCD is " + GCD(number1, number2)); } /** * Retrun GCD * * @param number1 * @param number2 * @return GCD */ static int GCD(int number1, int number2) { if (number1 % number2 == 0) return number2; else return (GCD(number2, number1 % number2)); } }
簡單運算元多載
MyString.cpp code
#include "stdafx.h" #include "MyString.h" #include <string.h> MyString &MyString::operator+ (const char* str) { static MyString backup; backup.assign(this->Getstring()); backup.append(str); return backup; } MyString &MyString::operator+ (MyString &str) { static MyString backup; backup.assign(this->Getstring()); backup.append(str.Getstring()); return backup; } MyString &MyString::operator= (const char *str) { this->assign(str); return *this; } MyString &MyString::operator= (MyString &str) { this->assign(str.Getstring()); return *this; } MyString::MyString(const char *str) { if(str==NULL) { Data=NULL; } else { Data=new char [strlen(str)+1]; strcpy(Data,str); } } MyString::~MyString() { if(Data!=NULL) delete [] Data; Data=NULL; } void MyString::assign(const char *str) { if(Data!=NULL) delete [] Data; Data=NULL; Data=new char [strlen(str)+1]; strcpy(Data,str); } void MyString::clean() { if(Data!=NULL) delete [] Data; Data=NULL; } int MyString::length() { return strlen(Data); } const char* MyString::Getstring() { return Data; } void MyString::append(const char *str) { if(Data==NULL) assign(str); else { char *Backup=new char [length()+1]; strcpy(Backup,Data); delete [] Data; Data=new char [strlen(Backup)+strlen(str)+1]; strcpy(Data,Backup); strcat(Data,str); delete [] Backup; } } char *MyString::token(char *str) { if(Data==NULL) return NULL; char *result=new char [length()+1]; int count=0; for(int i=0;i<length();i++) { // 檢查是否有token bool found=false; for(unsigned int j=0;j<strlen(str);j++) { if(Data[i]==str[j]) { //如果有找到 直接跳出 並 found=true found=true; break; } } if(!found) //沒找到表示要把目前處理的字元放到 result內 result[count++]=Data[i]; else { result[count]='\0'; // Backup the Left String char *backup=new char[length()-count+1]; int index=0; strcpy(backup,&Data[count+1]); //把剩下的重新給Data delete [] Data; Data=new char[strlen(backup)+1]; strcpy(Data,backup); delete [] backup; return result; } } result[count]='\0'; delete [] Data; Data=NULL; return result; }
簡單壓縮程式
Run_Length.h code
main.cpp code
#ifndef Run_Length #define Run_Length #include <fstream> using std::cout; using std::endl; using std::cerr; using std::ios; using std::fstream; using std::ifstream; using std::ofstream; using std::string; int Run_Length_Code(const char *input_filename, const char *output_filename ) { fstream f_in; //設定輸入流 fstream f_out;//設定輸出流 //開檔 並設為輸入和二位元讀取 f_in.open(input_filename,ios::binary|ios::in); if( !f_in ) //輸入檔錯誤 { cerr << "Input file ERROR!! " << endl; system("PAUSE"); exit(1); } //開檔 並設為輸出和二位元寫入 f_out.open(output_filename,ios::binary|ios::out); if( !f_out ) //輸出檔錯誤 { cerr << "Output file ERROR!! " << endl; system("PAUSE"); exit(1); } char temp,n,num,data,next; unsigned int Total_in=0,Total_out=0; int cont=0; //檔頭資訊檔 char ch[12] = {0, 255, 67, 72, 55, 95, 67, 83, 73, 69, 0, 255}; char head[12]; //檢查檔頭 是否已經壓縮過 int count = 0; bool check = false; for(int i = 0; i < 12; i++) { f_in.read(&head[i],1); if(ch[i] == head[i]) count++; } if(count==12) check = true; f_in.close(); //關檔 f_in.open(input_filename,ios::binary|ios::in);// 開檔 if (check) //有檔頭表示是壓縮過的 { //解壓縮 cout << "The "<< input_filename <<" is a uncompressed file, compressing …"; for (int i=0;i<sizeof(ch);i++) f_in.read(&temp,1); while( 1 ) { f_in.read(&n,1); if( !f_in ) break; //如果沒有資料就跳出 Total_out+=n; //計總共傳了多少 Total_in+=n; //計總共讀了多少 f_in.read(&temp,1); for(int i = 0; i < n; i++) f_out.write(&temp,1); } } else { //壓縮 bool ok=true; cout << "The "<< input_filename <<" is a compressed file, decompressing …\n"; f_out.write(ch,sizeof(ch)); //寫入壓縮檔頭 while ( 1 ) { if (ok) { f_in.read(&data,1); //讀入資料 Total_in++; //讀檔計數 } if( !f_in ) break;//若沒有資料就跳出 cont = 1; //重新開始數 while ( 1 ) { f_in.read(&next,1); Total_in++; //讀檔計數 if( !f_in ) { if(cont < 256) // 如果計數沒有大於256 { num = cont; f_out.write(&num,1); f_out.write(&data,1); break; } else //看超過幾次256次 { for(int i = 0; i < cont / 255; i++) { num = 255; f_out.write(&num,1); f_out.write(&data,1); Total_out+=256; } //再把剩下的數字輸出 num = cont % 255;; f_out.write(&num,1); f_out.write(&data,1); Total_out+=num; break; }//end of else }//end of if(!f_in) //f_in.read(&nextdata,1); //讀入下一筆資料 if ( data == next ) cont++; //當資料相同的時候 計數 if ( data != next ) { ok=false; if (cont < 256) // 如果計數沒有大於256 { num = cont; f_out.write(&num,1);//輸出次數 f_out.write(&data,1); // 輸出資料 Total_out+=2; data = next; break; } else { //看超過幾次256次 for(int i = 0; i < cont / 255; i++) { num = 255; f_out.write(&num,1); f_out.write(&data,1); Total_out+=256; } //再把剩下的數字輸出 num = cont % 255; f_out.write(&num,1); //f_out.write(&data,1); data = next; Total_out+=num; break; }//end of else }//end of if != }//end of while }//end of while }//end of 壓縮 f_in.close(); //關輸入檔 f_out.close(); //關輸出檔 return (Total_in-Total_out)/Total_in*100; } #endif
main.cpp code
#include <iostream> #include "Run_Length.h" using namespace std; int main(int argc, char *argv[]) { char in[255],out[255]; //存檔案的名子 cout << "Please enter input filename : "; cin >> in; //輸入檔名 cout << "Please enter output filename : "; cin >> out;//輸出檔名 int Rate; Rate=Run_Length_Code(in,out); //壓縮檔案or解壓縮 cout << "Finished. The compression rate : " << Rate << "%." << endl; system("PAUSE"); return EXIT_SUCCESS; }
LinkList in C++
main.cpp
http://pastie.org/255668
list.h
http://pastie.org/255677
#include <iostream> using std::cin; using std::endl; #include "list.h" int main() { List< int > L; int inputmax,front,back,tmpF,tmpB; bool ok; cout << "How much number do you want to input? "; cin >> inputmax; for (int i=0 ; i<inputmax; i++) { cout << "please enter "<< i+1 <<"th number =>"; cin >> back; if (i==0) { //第一次直接加入 L.insertAtBack(back); L.print(); } else if (i==1) { //第二次比較大加在前 比較小加在後 L.getFront(front); if (front>back) { //加在前 L.insertAtFront(back); L.print(); } else { //加在後 L.insertAtBack(back); L.print(); } } else { L.getFront(tmpF); //取得最前面的資料 L.getBack(tmpB); //取得最後面的資料 // cout << tmpF << " " << tmpB; if (back<tmpF) { L.insertAtFront(back); L.print(); } else if (tmpB<back) { L.insertAtBack(back); L.print(); } else { L.insert(back); L.print(); } } } return 0; }
http://pastie.org/255668
list.h
#ifndef LIST_H #define LIST_H #include <iostream> using std::cout; #include <new> #include "listnode.h" template< class NODETYPE > class List { public: List(); ~List(); void insertAtFront( const NODETYPE & ); void insertAtBack( const NODETYPE & ); void insert(const NODETYPE &); bool getFront( NODETYPE & ); bool getBack ( NODETYPE & ); bool removeFromFront( NODETYPE & ); bool removeFromBack( NODETYPE & ); bool isEmpty() const; void print() const; private: ListNode< NODETYPE > *firstPtr; ListNode< NODETYPE > *lastPtr; ListNode< NODETYPE > *getNewNode( const NODETYPE & ); }; template< class NODETYPE > List< NODETYPE >::List() : firstPtr( 0 ), lastPtr( 0 ) {} template< class NODETYPE > List< NODETYPE >::~List() { if ( !isEmpty() ) { cout << "Destroying nodes ...\n"; ListNode< NODETYPE > *currentPtr = firstPtr; ListNode< NODETYPE > *tempPtr; while ( currentPtr != 0 ) { // delete remaining nodes tempPtr = currentPtr; cout << " " << tempPtr->data ; currentPtr = currentPtr->nextPtr; delete tempPtr; } } cout << "\nAll nodes destroyed\n"; } template< class NODETYPE > //insertAtFront void List< NODETYPE >::insertAtFront( const NODETYPE &value ) { ListNode< NODETYPE > *newPtr = getNewNode( value ); if ( isEmpty() ) firstPtr = lastPtr = newPtr; else { newPtr->nextPtr = firstPtr; firstPtr = newPtr; } } template< class NODETYPE > //insert void List< NODETYPE >::insert( const NODETYPE &value ) { ListNode< NODETYPE > *newPtr = getNewNode( value ); ListNode< NODETYPE > *tempPtr = firstPtr; if ((newPtr->data)<(firstPtr->nextPtr->data)){ newPtr->nextPtr = firstPtr->nextPtr; firstPtr->nextPtr = newPtr; } else { while (!((newPtr->data)<(tempPtr->nextPtr->data))) { tempPtr = tempPtr->nextPtr; } newPtr->nextPtr = tempPtr->nextPtr; tempPtr->nextPtr = newPtr; } } template< class NODETYPE > //insertAtBack void List< NODETYPE >::insertAtBack( const NODETYPE &value ) { ListNode< NODETYPE > *newPtr = getNewNode( value ); if ( isEmpty() ) firstPtr = lastPtr = newPtr; else { lastPtr->nextPtr = newPtr; lastPtr = newPtr; } } template< class NODETYPE > //romoveFromFront bool List< NODETYPE >::removeFromFront( NODETYPE &value ) { if ( isEmpty() ) return false; else { ListNode< NODETYPE > *tempPtr = firstPtr; if ( firstPtr == lastPtr ) firstPtr = lastPtr = 0; else firstPtr = firstPtr->nextPtr; value = tempPtr->data; delete tempPtr; return true; } } template< class NODETYPE > //romoveFromBack bool List< NODETYPE >::removeFromBack( NODETYPE &value ) { if ( isEmpty() ) return false; else { ListNode< NODETYPE > *tempPtr = lastPtr; if ( firstPtr == lastPtr ) firstPtr = lastPtr = 0; else { ListNode< NODETYPE > *currentPtr = firstPtr; while ( currentPtr->nextPtr != lastPtr ) currentPtr = currentPtr->nextPtr; lastPtr = currentPtr; currentPtr->nextPtr = 0; } value = tempPtr->data; delete tempPtr; return true; } } template< class NODETYPE > //getFront bool List< NODETYPE >::getFront( NODETYPE &value ) { ListNode< NODETYPE > *tempPtr = firstPtr; value = tempPtr->data; return true; } template< class NODETYPE > //getBack bool List< NODETYPE >::getBack( NODETYPE &value ) { ListNode< NODETYPE > *tempPtr = lastPtr; value = tempPtr->data; return true; } template< class NODETYPE > //check isEmpty bool List< NODETYPE >::isEmpty() const { return firstPtr == 0; } template< class NODETYPE > //getNewNode ListNode< NODETYPE > *List< NODETYPE >::getNewNode( const NODETYPE &value ) { return new ListNode< NODETYPE >( value ); } template< class NODETYPE > //print Link void List< NODETYPE >::print() const { if ( isEmpty() ) { cout << "The list is empty\n\n"; return; } ListNode< NODETYPE > *currentPtr = firstPtr; cout << "list: "; while ( currentPtr != 0 ) { cout << currentPtr->data << ' '; currentPtr = currentPtr->nextPtr; } cout << "\n"; } #endif !!listnode.h #ifndef LISTNODE_H #define LISTNODE_H template< class NODETYPE > class List; template< class NODETYPE > class ListNode { friend class List< NODETYPE >; public: ListNode( const NODETYPE & ); NODETYPE getData() const; //getDate private: NODETYPE data; //save data ListNode< NODETYPE > *nextPtr; }; template< class NODETYPE > ListNode< NODETYPE >::ListNode( const NODETYPE &info ) : data( info ), nextPtr( 0 ) {} template< class NODETYPE > NODETYPE ListNode< NODETYPE >::getData() const { return data; } #endif
http://pastie.org/255677
QueueSort in C++
main.cpp
http://pastie.org/255656
q2.h
http://pastie.org/255658
#include <iostream> using std::cout; using std::cin; using std::endl; #include "q2.h" int main() { int inputmax,tmp,check; inputmax=5; bool ok; Queue QueueSort; #ifdef DEBUGs //Debug QueueSort.add(8); QueueSort.add(1); QueueSort.around(); QueueSort.around(); QueueSort.around(); QueueSort.around(); QueueSort.around(); // cout << "del is:"<<QueueSort.del()<<"\n"; cout << "getfront:" << QueueSort.getfront() << "getrear" << QueueSort.getrear(); #endif for (int i=0 ; i<inputmax; i++) { ok=true; cout << "please enter "<< i+1 <<"th number =>"; cin >> tmp; if (i < 2) { QueueSort.add(tmp); QueueSort.pr(); } else { // QueueSort.del(check); check=QueueSort.getfront(); // tmp=QueueSort.getrear(); #ifdef DEBUG //Debug cout << "front:" << check << " rear:" << tmp << " "; QueueSort.pr(); #endif while (ok) { if (check < tmp) { //front < input #ifdef DEBUG //Debug cout << "add-cin check:" << check << " tmp:" << tmp << " "; QueueSort.pr(); #endif QueueSort.add(tmp); QueueSort.pr(); ok=false; } else { QueueSort.around(); // QueueSort.add(tmp); QueueSort.pr(); } check=QueueSort.getfront(); } #ifdef DEBUGs //Debug int aa; cin >> aa; #endif cout << "Sort Number:\n"; do { if (QueueSort.getfront()>QueueSort.getrear()) { QueueSort.pr(); //break; } else { QueueSort.around(); QueueSort.pr(); } } while (QueueSort.getfront()<QueueSort.getrear()); } } return 0; }
http://pastie.org/255656
q2.h
#ifndef QUEUE_H #define QUEUE_H class Queue { public: Queue(); void qFull(); void qEmpty(); void add(const int x); int del(); int getfront(); int getrear(); void pr(); void around(); bool IsFull(); bool IsEmpty(); private: int front,rear; int q[6]; int max; }; Queue::Queue() { front=-1; rear=-1; max=6; for (int i=0;i<max;i++) q[i]=0; } void Queue::qFull() { cout << "\nQueue is Full!!\n";//傳出滿了 } void Queue::qEmpty() { cout << "\nQueue is Empty!!\n";//傳出空的 } inline void Queue::add(const int x) { #ifdef DEBUG //Debug cout << "before add() front:" << front << " rear:" << rear << " "; pr(); #endif int newrear=(rear+1)%max; //測滿了沒 if (front==newrear) qFull(); //如果滿了就不加 else q[rear=newrear]= x; //若沒有就加入 #ifdef DEBUG //Debug cout << " after add() front:" << front << " rear:" << rear << " "; pr(); #endif } inline bool Queue::IsFull() { if (rear==(max-1)) return true; else return false; } inline bool Queue::IsEmpty() { if (front==rear) return true; else return false; } inline int Queue::del() { #ifdef DEBUG //Debug cout << "before del() front:" << front << " rear:" << rear << " "; pr(); #endif int x; if (front==rear) { qEmpty(); return 0; } else { front=(front+1)%max; x = q[front]; //傳回值 q[front]=0; //清除 } #ifdef DEBUG //Debug cout << " after del() front:" << front << " rear:" << rear <<" "; pr(); #endif return x; } int Queue::getfront() { int newfront=(front+1)%max; #ifdef DEBUG //Debug cout << "getfront() newfront:" << newfront << " rear:" << rear << " q:" << q[newfront] <<"\n"; #endif return q[newfront]; } int Queue::getrear() { #ifdef DEBUG //Debug cout << "getrear() front:" << front << " rear:" << rear << " q:"<<q[rear] <<"\n"; #endif return q[rear]; } inline void Queue::pr() { //print from first to rear cout << "List:"; int newfront=(front+1)%max; int newrear=(rear+1)%max; for (int i=0;i<max-1;i++) { cout << " " << q[newfront]; newfront=(newfront+1)%max; // cout << " " <<q[i]; } cout << "\n"; } void Queue::around() { //旋轉 #ifdef DEBUG //Debug cout << "Start Around\n"; #endif add(del()); #ifdef DEBUG //Debug cout << "End Around\n"; #endif } #endif
http://pastie.org/255658
訂閱:
文章 (Atom)