標籤:head == nbsp isp new code char ram 對象
1.Java問題
public class CharTest { String str=new String("good"); char[] ch={‘a‘,‘b‘,‘c‘}; public static void main(String args[]) { InterContents info=new InterContents(); CharTest ex=new CharTest(); ex.change(ex.str,ex.ch); System.out.println(ex.str+"and"); System.out.println(ex.ch); } public void change(String str,char ch[]) { str="test ok"; ch[0]=‘g‘;; }}
輸出結果為:
goodand
gbc
注釋:JAVA不同於C++,Java只有按值傳遞(基本類型就是通常說的按值傳遞,對象是傳對象引用副本的值,所以也叫按值傳遞),ch之所以改變是因為它根據ch對象的引用製作了一個引用的副本傳給函數,而數組裡的元素的改變會引起ch這個數組對象的改變。另外你要是給函數不傳數組,只傳單個char,那麼就和str一樣不會改變了
2.實現單鏈表的反轉
public class Node { Node next; int value; public Node(int value) { this.value = value; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }
/** * * 實現單鏈表的反轉 */ public static void main(String args[]) { CharTest charTest=new CharTest(); Node head=new Node(0); Node node1=new Node(1); Node node2=new Node(2); Node node3=new Node(3); Node node4=new Node(4); Node node5=new Node(5); head.setNext(node1); node1.setNext(node2); node2.setNext(node3); node3.setNext(node4); node4.setNext(node5); node5.setNext(null); Node head1=charTest.Reverse1(head); charTest.display(head1); } /** * * @param n 頭結點 * 方法:輸出鏈表的所有的value值 */ public void display(Node n){ if(n!=null){ System.out.println("輸出的value:"+n.getValue()); display(n.next); } else{ System.out.println("輸出的value為NULL"); } } public static Node Reverse1(Node head) { if (head == null || head.getNext() == null) { return head; } Node reHead = Reverse1(head.getNext()); head.getNext().setNext(head); head.setNext(null); return reHead; }
注釋:遞迴反轉的方法是copy來的
Android面試題