Java反轉單鏈表(code)

來源:互聯網
上載者:User

標籤:

主要是面試中可能會經常碰上該類似操作,尤其是稍大點公司,面試官可能並不在乎你能不能搞定該題,但是這類型題目最是能體現程式員的思維狀態 ---一個迷糊頭腦的程式員 怎能立志改變這個世界

/** * @author luochengcheng * 定義一個單鏈表 */class Node {//變數private int record;//指向下一個對象private Node nextNode;public Node(int record) {super();this.record = record;}public int getRecord() {return record;}public void setRecord(int record) {this.record = record;}public Node getNextNode() {return nextNode;}public void setNextNode(Node nextNode) {this.nextNode = nextNode;}}/** * @author luochengcheng *兩種方式實現單鏈表的反轉(遞迴、普通) *新手強烈建議旁邊拿著紙和筆跟著代碼畫圖(便於理解) */public class ReverseSingleList {/**  * 遞迴,在反轉當前節點之前先反轉後續節點  */public static Node reverse(Node head) {if (null == head || null == head.getNextNode()) {return head;}Node reversedHead = reverse(head.getNextNode());head.getNextNode().setNextNode(head);head.setNextNode(null);return reversedHead;}/**  * 遍曆,將當前節點的下一個節點緩衝後更改當前節點指標  *   */public static Node reverse2(Node head) {if (null == head) {return head;}Node pre = head;Node cur = head.getNextNode();Node next;while (null != cur) {next = cur.getNextNode();cur.setNextNode(pre);pre = cur;cur = next;}//將原鏈表的前端節點的下一個節點置為null,再將反轉後的前端節點賦給head   head.setNextNode(null);head = pre;return head;}public static void main(String[] args) {Node head = new Node(0);Node tmp = null;Node cur = null;// 構造一個長度為10的鏈表,儲存前端節點對象head   for (int i = 1; i < 10; i++) {tmp = new Node(i);if (1 == i) {head.setNextNode(tmp);} else {cur.setNextNode(tmp);}cur = tmp;}//列印反轉前的鏈表Node h = head;while (null != h) {System.out.print(h.getRecord() + " ");h = h.getNextNode();}//調用反轉方法head = reverse2(head);System.out.println("\n**************************");//列印反轉後的結果while (null != head) {System.out.print(head.getRecord() + " ");head = head.getNextNode();}}}

 

Java反轉單鏈表(code)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.