Java實現單鏈表翻轉

來源:互聯網
上載者:User

標籤:單鏈表   鏈表翻轉   遞迴   

單鏈表翻轉比如有如下鏈表:

     

需要按照C B A 輸出,我們可以有好幾種方法:

package org.andy.test;import java.util.ArrayList;import java.util.List;/** * @author andy * @version:2015-2-4 上午9:41:12 *  *  */public class LinkedReverse {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubN n = new N();n.name = "A";N n1 = new N();n1.name = "B";N n2 = new N();n2.name = "C";N n3 = new N();n3.name = "D";n1.nextN = n2;n.nextN = n1;n2.nextN = n3;N old = n;while (old != null) {System.out.println(old.name);old = old.nextN;}System.out.println("鏈表翻轉1");N new1 = reverseOne(n);while (new1 != null) {System.out.println(new1.name);new1 = new1.nextN;}/*System.out.println("鏈表翻轉2");N new2 = reverseTwo(n, null);while (new2 != null) {System.out.println(new2.name);new2 = new2.nextN;}System.out.println("鏈表翻轉3");N new3 = reverseThree(n);while (new3 != null) {System.out.println(new3.name);new3 = new3.nextN;}*/}//採用交換前後值public static N reverseOne(N n) {if (n != null) {N preN = n; //前一個節點N curN = n.nextN; //當前節點N nextN ;   //後一個節點while (null != curN) {nextN = curN.nextN;curN.nextN = preN;preN = curN;curN = nextN;}n.nextN = null;n = preN;return n;}return null;}//採用遞迴實現public static N reverseTwo(N n, N newN) {// 採用遞迴 返回 返回條件是最後一個幾點nextN為空白if (n == null) {return newN;}N nextN = n.nextN;n.nextN = newN;return reverseTwo(nextN, n);}//最爛的實現方式public static N reverseThree(N n) {if (n == null) {return null;}// 定義一個集合 ,放在集合裡面在單個反向指回List<N> nList = new ArrayList<N>();N p = n;while (p != null) {N node = new N();// 當前節點node.name = p.name;nList.add(node);p = p.nextN;}// 在返現輸出節點n = null;for (N rn : nList) {if (n != null) {// 如果n不為空白時rn.nextN = n;}n = rn;}return n;}}// 定義一個節點class N {public String name;public N nextN;}


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.