2011年4月30日 星期六

Fibonacci number

---------Java not recursice------------------------------

int maxnumber = 1000;
Vector< Integer > F_array = new Vector< Integer >();

F_array.SetElementAt( 0, 0);
F_array.SetElementAt( 1, 1);

for ( int i = 2 ; i < maxnumber ; i++ ) {

F_array.SetElementAt( i, F_array.ElementAt(i-1) + F_array.ElementAt(i-2) );

} // for

---------Java recursice------------------------------------

int FibonacciNumber( int index ) {

if ( index > 1 ) {
return FibonacciNumber( index-1 ) + FibonacciNumber( index-2 ) ;
} // if
else if ( index == 1 ) {
return 1;
} // else if
else {
return 0;
} // else


}

Single Linked List Reverse

假設有3個指標:
head指向linked list頭,
cur指向linked list頭,
nextprocess指向null.

if ( cur->next->next != null ) {
cur->next->next = nextprocess;
// 將第三個node先用nextprocess指著


cur->next->next = cur;
head = cur->next;
cur->next = null;

do {
cur = nextprocess;
if ( nextprocess->next != null ) {
nextprocess = nextprocess->next;
// 檢查是否後面還有node
} // if

cur->next = head;
head = cur;
} while ( nextprocess != null )

} // if
else {
//此linked list可能只有0-2個node
} // else