JAVA實現單向鏈表反轉__Java

來源:互聯網
上載者:User

《單向鏈表反轉》 最近正在面試,求職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;}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.