《單向鏈表反轉》 最近正在面試,求職Android應用方向的工作。基礎知識還可以,但是演算法,呵呵。做手機用戶端的基本涉及演算法不多,大多是架構設計,解耦,以及功能最佳化,UI,IO等。好了廢話不多說。進入正題。
單向鏈表,你懂得。再此不多做解釋。單向鏈表的反轉,時間複雜度,空間複雜度低一些才是好演算法嗎。基本目前是做到了O(n).思路就是,聲明三個引用pre,cur,tempNext,pre,cur分別指向第一個元素和第二個元素。tempNext存住第三個元素的引用。反轉前兩個,p2---->p1 (注意此時p2.next 已斷開)需要原來指向第二個的引用指向第三個,既pre,cur移動到p2,p3 ,也就是pre 引用p2, cur引用p3 .跟第一次pre,cur分別指向p1,p2類似,如此往複下去. 需要注意的幾點, 1 本身JAVA代碼,需要注意Java是值傳遞還是引用傳遞。如果不注意的話,變數交換就會有問題。真的,親。 2 各種臨時變數的記錄。不要繞暈了。同時也要注意上一點。
上代碼。。。自己寫的,可運行。
</pre><pre name="code" class="java">package com.main;public class Main {public static void main(String[] args) {String [] str={"11","2","45","67","23","44","55","89","74","10"};RevertListfromHead rl= new RevertListfromHead(str);}}package com.main;public class RevertListfromHead {public RevertListfromHead(String[] str) {MyLinkList mList = new MyLinkList(str);mList.printList(mList.head); System.out.println("--------------------------");System.out.println("after revert list is ");mList.head=mList.revertLinkedList(mList.head);mList.printList(mList.head);}class MyLinkList {private Node head;private int mlength; public MyLinkList(String[] str) {head = new Node(str[0]);Node currentNode = head;for (int i = 1; i < str.length; i++) {currentNode.next = new Node(str[i]);currentNode = currentNode.next;}mlength = str.length;}public Node revertLinkedList(Node _head) {int sum=0;if (null == _head) { return head; } Node pre = _head; Node cur = _head.next; Node tempnext; while (null != cur) { tempnext = cur.next; cur.next=pre; pre = cur; cur = tempnext; sum++; } //將原鏈表的前端節點的下一個節點置為null,再將反轉後的前端節點賦給head head.next=null; head = pre; return head; }public void printList(Node _head) {Node tempNode = _head;while (tempNode != null) {System.out.println("current data is : " + tempNode.data);tempNode = tempNode.next;}}}static class Node {String data;Node next;public Node(String _data) {this.data = _data;}}}