在面試,筆試的過程當中常常會遇到面試官問這種問題,實現單鏈表的倒置方法。如今對單鏈表的倒置犯法作個記錄,方便本身之後查看。面試
單鏈表的定義:ide
1 public class Node { 2 3 int v; 4 Node next; 5 public Node(){ 6 } 7 public Node(int v){ 8 this.v = v; 9 } 10 11 public int getV() { 12 return v; 13 } 14 public void setV(int v) { 15 this.v = v; 16 } 17 public Node getNext() { 18 return next; 19 } 20 public void setNext(Node next) { 21 this.next = next; 22 } 23 }
單鏈表的倒置方法有兩種:遞歸的和非遞歸的。下邊分別介紹:函數
遞歸:this
1 public static Node reverse(Node head){ 2 if(head == null || head.next==null){ 3 return head; 4 } 5 Node reverseHead = reverse1(head.next); 6 head.getNext().setNext(head); 7 head.setNext(null); 8 return reverseHead; 9 }
非遞歸:spa
1 /** 2 * 非遞歸實現 3 * @param head 4 * @return 5 */ 6 public static Node reverse(Node head){ 7 if (head == null) return head; 8 Node pNode=head; 9 Node cur = head.next; 10 Node nNode=null; 11 while(cur!=null){ 12 nNode = cur.next; 13 cur.setNext(pNode); 14 pNode = cur; 15 cur = nNode; 16 } 17 head.setNext(null); 18 return pNode; 19 }
遞歸與非遞歸的實現和斐波那契函數的非遞歸實現很像。3d