文件一:ListNode.java java 代码 public class ListNode { char element; //当前字符 int count; //字符个数 ListNode next; ListNode(char c,ListNode n) { element = c; count=1; next=n; } ListNode(char c) { this(c,null); } } LinkedList.java java 代码 public class LinkedList { ListNode header; LinkedList() { this(null); } LinkedList(ListNode n) { header=new ListNode(' ',n); } boolean isEmpty() { return header.next==null; } void makeEmpty() { header=null; } ListNode find(char c) { if(isEmpty()) return null; ListNode node = header.next; while(node!=null) { if(node.element==c) return node; node=node.next; } return null; } void insert(char c,ListNode node) { node.next=new ListNode(c,node.next); } void remove(char c) { if(isEmpty()) return; ListNode node = header.next; while(node!=null) { if(node.next.element==c) { node.next=node.next.next; return; } node = node.next; } } } 文件三:Test.java java 代码 public class Test { public static void showCharCount(char s[]) { System.out.println("原字符串是:"+new String(s)); LinkedList list = new LinkedList(); ListNode node; for(int i=0; i s.length; i++) { if((node=list.find(s[i]))==null) list.insert(s[i],list.header); else node.count++; } /* * 打印链表 */ node = list.header.next; while(node!=null&&!list.isEmpty()) { System.out.println("字符: '" +node.element+"' 出现: " +node.count+" 次"); node=node.next; } } public static void showCharCount(String s) { showCharCount(s.toCharArray()); } public static void main(String[] args) { showCharCount("abcd ssd wool"); } } 最后修饰下,把main方法写漂亮点: java 代码 public static void main(String[] args) throws IOException{ String s; while(true) { System.out.print("请输入待统计字符串: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); s = br.readLine(); if(s.length()>=40) { System.out.println("请输入40个字符以内."); System.out.println("===============================\n"); continue; } else break; } showCharCount(s); } 效果如下: 请输入待统计字符串: Woden!Never give up!!!I'll do my best!!! 请输入40个字符以内. =============================== 请输入待统计字符串: Woden!Never give up!!! 原字符串是:Woden!Never give up!!! 字符: 'p' 出现: 1 次 字符: 'u' 出现: 1 次 字符: 'i' 出现: 1 次 字符: 'g' 出现: 1 次 字符: ' ' 出现: 2 次 字符: 'r' 出现: 1 次 字符: 'v' 出现: 2 次 字符: 'N' 出现: 1 次 字符: '!' 出现: 4 次 字符: 'n' 出现: 1 次 字符: 'e' 出现: 4 次 字符: 'd' 出现: 1 次 字符: 'o' 出现: 1 次 字符: 'W' 出现: 1 次
LinkedList.java
文件三:Test.java
最后修饰下,把main方法写漂亮点:
效果如下: 请输入待统计字符串: Woden!Never give up!!!I'll do my best!!! 请输入40个字符以内. =============================== 请输入待统计字符串: Woden!Never give up!!! 原字符串是:Woden!Never give up!!! 字符: 'p' 出现: 1 次 字符: 'u' 出现: 1 次 字符: 'i' 出现: 1 次 字符: 'g' 出现: 1 次 字符: ' ' 出现: 2 次 字符: 'r' 出现: 1 次 字符: 'v' 出现: 2 次 字符: 'N' 出现: 1 次 字符: '!' 出现: 4 次 字符: 'n' 出现: 1 次 字符: 'e' 出现: 4 次 字符: 'd' 出现: 1 次 字符: 'o' 出现: 1 次 字符: 'W' 出现: 1 次