Java反轉(zhuǎn)鏈表測試過程介紹
導讀
本文主體為單項鏈表和雙向鏈表的反轉(zhuǎn)以及簡單的測試,以便于理解鏈表相關的算法題目。
鏈表
特點
- 便于增刪數(shù)據(jù),不便于尋址
- 在內(nèi)存中屬于跳轉(zhuǎn)結構
單鏈表和雙鏈表的定義
單鏈表: 值,一條next指針
雙鏈表:值,一條last指針,一條next指針
單向鏈表
Node結點
public static class Node { public int value; public Node next; public Node(int value) { this.value = value; } @Override public String toString() { ArrayList<Integer> nums = new ArrayList<>(); Node node = this; while (node != null) { nums.add(node.value); node = node.next; } return nums.toString(); } }
反轉(zhuǎn)單向鏈表
public static Node reverseLinkedList(Node head) { Node next = null; Node pre = null; while (head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; }
測試函數(shù)
public static void main(String[] args) { Node node = new Node(1); node.next = new Node(2); node.next.next = new Node(3); node = reverseLinkedList(node); System.out.println(node); }
輸出結果如下:
[3, 2, 1]
雙向鏈表
Node結點
public static class DoubleList { public int value; public DoubleList next; public DoubleList last; public DoubleList(int value) { this.value = value; } @Override public String toString() { ArrayList<Integer> nums = new ArrayList<>(); DoubleList node = this; while (node != null) { nums.add(node.value); node = node.next; } return nums.toString(); } }
反轉(zhuǎn)雙向鏈表
public static DoubleList reverseDoubleList(DoubleList head) { DoubleList next; DoubleList pre = null; while (head != null) { next = head.next; head.next = pre; // 注意和單項鏈表不一樣的地方只有這一行,其他都基本一樣 head.last = next; pre = head; head = next; } return pre; }
測試代碼
public static void main(String[] args) { DoubleList node1 = new DoubleList(1); node1.next = new DoubleList(2); node1.next.last = node1; node1.next.next = new DoubleList(3); node1.next.next.last = node1.next; System.out.println("reverseDoubleList(node1) = " + reverseDoubleList(node1)); }
輸出結果如下:
reverseDoubleList(node1) = [3, 2, 1]
到此這篇關于Java反轉(zhuǎn)鏈表測試過程介紹的文章就介紹到這了,更多相關Java反轉(zhuǎn)鏈表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring如何集成ibatis項目并實現(xiàn)dao層基類封裝
這篇文章主要介紹了Spring如何集成ibatis項目并實現(xiàn)dao層基類封裝,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09詳解@Autowired(required=false)注入注意的問題
這篇文章主要介紹了@Autowired(required=false)注入注意的問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04使用SpringBoot和JPA實現(xiàn)批量處理新增、修改
最近項目需要在JPA中使用ID進行批量更新,所以下面這篇文章主要給大家介紹了關于使用SpringBoot和JPA實現(xiàn)批量處理新增、修改的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-06-06Spring Boot使用模板freemarker的示例代碼
本篇文章主要介紹了Spring Boot使用模板freemarker的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10Spring Boot+Shiro實現(xiàn)一個Http請求的Basic認證
本文向向大家仔細的介紹了如何使用Shiro實現(xiàn)一個Http請求的Basic認證,有此需求的朋友可以參考下本文2021-06-06Spring Cloud根據(jù)服務名獲取服務的ip端口問題
這篇文章主要介紹了Spring Cloud根據(jù)服務名獲取服務的ip端口,本篇示例我就以Nacos注冊中心為例了,下面是我注冊的兩個服務,需要的朋友可以參考下2022-09-09