Java-反轉單鏈表

來源:互聯網
上載者:User

標籤:java   反轉單鏈表   

單鏈表的反轉比較簡單,迭代和遞迴都可以做。

先定義一個類用於表示單鏈表中的結點:

public class ListNode {private int val;private ListNode next;public ListNode(int value){this.val = value;this.next = null;}public int getVal() {return val;}public void setVal(int val) {this.val = val;}public ListNode getNext() {return next;}public void setNext(ListNode next) {this.next = next;}}

迭代的方法:

/** * 遍曆,雙指標一前一後同時向尾部移動 * @param head 要反轉的鏈表的頭結點 * @return */public static ListNode reverse(ListNode head){if(head==null){return head;}ListNode pre = head; //前一個指標ListNode cur = head.getNext();  //後一個指標ListNode next;//臨時對象,指標後移時要用到的while(cur != null){next = cur.getNext();cur.setNext(pre);pre = cur; //指標後移cur = next;//指標後移}//一定記得把初始鏈表頭結點的next置為null,因為反轉後它將會是最後一個結點head.setNext(null);//把頭結點設為反轉後鏈表的第一個結點,然後返回就okhead = pre;return head;}

遞迴的方法:

/** * 遞迴思想 * 在翻轉當前節點之前,如果該節點有後續節點,先翻轉其後續節點 * 如果該節點沒有子節點,就把該節點的next指向其父節點,並把父節點的next置為null * @param head * @return */public static ListNode reverse(ListNode head){//當前結點為null,或者當前結點沒有後續結點時,遞迴退出if(head.getNext()==null || head==null){return head;}//當前結點不為null並且有next時,遞迴去反轉它的後續結點ListNode tempNode = reverse(head.getNext());//反轉當前結點和它的子結點head.getNext().setNext(head);head.setNext(null);return tempNode;}

測試函數:

public static void main(String[] args){ListNode node1 = new ListNode(1);ListNode node2 = new ListNode(2);ListNode node3 = new ListNode(3);ListNode node4 = new ListNode(4);node1.setNext(node2);node2.setNext(node3);node3.setNext(node4);node1 = reverse(node1);while(node1 != null){System.out.print(node1.getVal()+" ");node1 = node1.getNext();}}


Java-反轉單鏈表

聯繫我們

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