java 單鏈表list 轉置(反轉) 普通與遞迴

2021-08-14 03:07:47 字數 1273 閱讀 8692

單鏈表的轉置 (反轉) 

普通方法  通過迴圈與臨時變數來轉置   優點是節省記憶體開銷

public void commonreverse()

}

解析:當list = a1 a2 a3 a4 時

運算方式

第一輪:curr = a1 ; temp = a1 ; curr = a2 ; a1.next = null ; reve = a1;

第二輪:curr = a2 ; temp = a2 ; curr = a3 ; a2.next = a1 ; reve = a2;

第三輪:curr = a3 ; temp = a3 ; curr = a4 ; a3.next = a2 ; reve = a3;

第四輪:curr = a4 ; temp = a4 ; curr = null; a4.next = a3;reve = a4;

消耗記憶體最小 也容易理解

遞迴演算法

public node recursionreverse(node head)

node tail = recursionreverse(head);

head.next.next = head;

head.next = null;

return tail;

}

解析:當list = a1 a2 a3 a4 時

運算方式

第一輪 : head = a1; head.next.next = head; head.next =null; 兩個方法壓入棧中 其中head = a1;

第二輪 : head = a2; head.next.next = head;

head.next =null; 兩個方法壓入棧中 其中head = a2;

第三輪 : head = a3; head.next.next = head;

head.next =null; 兩個方法壓入棧中 其中head = a3;

第四輪 : head = a4; 返回方法棧 取出第三輪剩餘方法執行

第三輪剩餘方法:head = a3 ; a3.next = a4 ; a4.next = a3; a3.next = null;

第二輪剩餘方法:head = a2 ; a2.next = a3 ; a3.next = a2; a2.next = null;

第一輪剩餘方法:head = a1 ; a1.next = a2 ; a2.next = a1; a1.next = null; 完畢

單鏈表轉置

編寫乙個單鏈表反序的函式 include include typedef int datatype using namespace std typedef struct node node void initnode node head void printnode node head cout e...

單鏈表轉置

單鏈表轉置都很熟裡,這裡只是練一下鍊錶操作,另外還有幾點需要注意,如果是遞迴解決該問題呢,如果是相鄰兩個轉置有怎麼處理。1.單鏈表轉置非遞迴 void reverse struct node list list pleft 2.單鏈表轉置遞迴 struct node recursive revers...

單鏈表轉置

關於單鏈表的逆置,大家都很清楚有兩種基本方法 1 普通的迴圈的方法。2 遞迴呼叫方法。今天正好研究這兩種方法,發現很不理解 這麼寫的具體的作用,誠如很多人所說,吃透這個還是要自己畫乙個詳細的過程圖。今天就給大家介紹一下 普通的迴圈方法 我學習下來的一些經驗,如有不對之處還望大家一起交流。首先,以下是...