Java實現(xiàn)單鏈表翻轉(zhuǎn)實例代碼
Java實現(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é)點
while (head != null) {
Node cur = head.next;// 記錄下一個節(jié)點
head.next = reHead;// 將rehead節(jié)點連接到head節(jié)點上
reHead = head;// 讓rehead指向head
head = cur;// 將head指向下一個節(jié)點
}
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é)點置于末端
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);
}
}
運行結(jié)果如下:

以上所述是小編給大家介紹的Java實現(xiàn)單鏈表翻轉(zhuǎn)實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Java中將List拆分為多個小list集合的實現(xiàn)代碼
這篇文章主要介紹了Java中如何將List拆分為多個小list集合,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
Java 替換字符串右側(cè)出現(xiàn)的第一個子串方式
這篇文章主要介紹了Java 替換字符串右側(cè)出現(xiàn)的第一個子串方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Spring Cloud Feign接口返回流的實現(xiàn)
這篇文章主要介紹了Spring Cloud Feign接口返回流的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10
SpringBoot統(tǒng)一返回JSON格式實現(xiàn)方法詳解
這篇文章主要介紹了SpringBoot統(tǒng)一返回JSON格式實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-02-02
mybatis攔截器實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)權(quán)限隔離方式
通過Mybatis攔截器,在執(zhí)行SQL前添加條件實現(xiàn)數(shù)據(jù)權(quán)限隔離,特別是對于存在用戶ID區(qū)分的表,攔截器會自動添加如user_id=#{userId}的條件,確保SQL在執(zhí)行時只能操作指定用戶的數(shù)據(jù),此方法主要應用于Mybatis的四個階段2024-11-11
SpringBoot獲取yml和properties配置文件的內(nèi)容
這篇文章主要為大家詳細介紹了SpringBoot獲取yml和properties配置文件的內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

