Java反轉鏈表測試過程介紹
更新時間:2023年04月12日 11:26:41 作者:ziop-三月
這篇文章主要介紹了Java反轉鏈表測試過程,學習過數(shù)據結構的小伙伴們,對鏈表想來是并不陌生。本篇文章將為大家介紹幾種在Java語言當中,實現(xiàn)鏈表反轉的幾種方法,以下是具體內容
導讀
本文主體為單項鏈表和雙向鏈表的反轉以及簡單的測試,以便于理解鏈表相關的算法題目。
鏈表
特點
- 便于增刪數(shù)據,不便于尋址
- 在內存中屬于跳轉結構
單鏈表和雙鏈表的定義
單鏈表: 值,一條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();
}
}反轉單向鏈表
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();
}
}反轉雙向鏈表
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反轉鏈表測試過程介紹的文章就介紹到這了,更多相關Java反轉鏈表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java二維數(shù)組與稀疏數(shù)組相互轉換實現(xiàn)詳解
在某些應用場景中需要大量的二維數(shù)組來進行數(shù)據存儲,但是二維數(shù)組中卻有著大量的無用的位置占據著內存空間,稀疏數(shù)組就是為了優(yōu)化二維數(shù)組,節(jié)省內存空間2022-09-09
java實現(xiàn)cassandra高級操作之分頁實例(有項目具體需求)
這篇文章主要介紹了java實現(xiàn)cassandra高級操作之分頁實例(有項目具體需求),具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04
Mybatisplus創(chuàng)建Spring?Boot工程打包錯誤的解決方式
最近在實戰(zhàn)springboot遇到了一些坑,記錄一下,下面這篇文章主要給大家介紹了關于Mybatisplus創(chuàng)建Spring?Boot工程打包錯誤的解決方式,文中通過圖文介紹的介紹的非常詳細,需要的朋友可以參考下2023-03-03

