Java實(shí)現(xiàn)單鏈表翻轉(zhuǎn)實(shí)例代碼
Java實(shí)現(xiàn)單鏈表反轉(zhuǎn),遞歸和非遞歸兩種形式
/**
* 反轉(zhuǎn)單鏈表
*/
/** * 定義鏈表
*
* @author 16026
*
*/
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
public class ReverseList {
/**
* 反轉(zhuǎn)鏈表
*
* @param head
* @return
*/
public static Node reverseList(Node head) {
if (head == null || head.next == null) {
return head;
}
Node reHead = null;// 定義新鏈表頭結(jié)點(diǎn)
while (head != null) {
Node cur = head.next;// 記錄下一個(gè)節(jié)點(diǎn)
head.next = reHead;// 將rehead節(jié)點(diǎn)連接到head節(jié)點(diǎn)上
reHead = head;// 讓rehead指向head
head = cur;// 將head指向下一個(gè)節(jié)點(diǎn)
}
return reHead;
}
/**
* 遞歸反轉(zhuǎn)鏈表
*
* @param head
* @return
*/
public static Node reverseList2(Node head) {
if (head == null || head.next == null)
return head;
Node rehead = reverseList2(head.next);
head.next.next = head;// 將頭節(jié)點(diǎn)置于末端
head.next = null;// 防止鏈表循環(huán)
return rehead;
}
/**
* 打印鏈表
*
* @param head
*/
public static void printList(Node head) {
if (head == null)
return;
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
/**
* 測試
*
* @param args
*/
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
// Node rehead = reverseList(n1);
Node rehead = reverseList2(n1);
printList(rehead);
}
}
運(yùn)行結(jié)果如下:

以上所述是小編給大家介紹的Java實(shí)現(xiàn)單鏈表翻轉(zhuǎn)實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
最新IDEA?2022基于JVM極致優(yōu)化?IDEA啟動(dòng)速度的方法
這篇文章主要介紹了IDEA?2022最新版?基于?JVM極致優(yōu)化?IDEA?啟動(dòng)速度,需要的朋友可以參考下2022-08-08
spring cloud hystrix 超時(shí)時(shí)間使用方式詳解
這篇文章主要介紹了spring cloud hystrix 超時(shí)時(shí)間使用方式,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
java?list和map切割分段的實(shí)現(xiàn)及多線程應(yīng)用案例
這篇文章主要為大家介紹了java?list和map切割分段的實(shí)現(xiàn)及多線程應(yīng)用案例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Nacos框架服務(wù)注冊實(shí)現(xiàn)流程
這篇文章主要介紹了SpringCloud服務(wù)注冊之nacos實(shí)現(xiàn)過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
springboot實(shí)現(xiàn)攔截器的3種方式及異步執(zhí)行的思考
實(shí)際項(xiàng)目中,我們經(jīng)常需要輸出請求參數(shù),響應(yīng)結(jié)果,方法耗時(shí),統(tǒng)一的權(quán)限校驗(yàn)等。本文首先為大家介紹 HTTP 請求中三種常見的攔截實(shí)現(xiàn),并且比較一下其中的差異。感興趣的可以了解一下2021-07-07
Java之String字符串在JVM中的存儲(chǔ)及其內(nèi)存地址的問題
這篇文章主要介紹了Java之String字符串在JVM中的存儲(chǔ)及其內(nèi)存地址的問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
Java實(shí)現(xiàn)List反轉(zhuǎn)的方法總結(jié)
在Java中,反轉(zhuǎn)一個(gè)List意味著將其元素的順序顛倒,使得第一個(gè)元素變成最后一個(gè),最后一個(gè)元素變成第一個(gè),依此類推,這一操作在處理數(shù)據(jù)集合時(shí)非常有用,所以本文給大家總結(jié)了Java實(shí)現(xiàn)List反轉(zhuǎn)的方法,需要的朋友可以參考下2024-04-04

