40道java经典算法(四)(31-40)

/*【程序31】
题目:求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;
   }
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值