這篇文章將為大家詳細講解有關使用Java如何翻轉單鏈表,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
創新互聯建站基于分布式IDC數據中心構建的平臺為眾多戶提供電信機房托管 四川大帶寬租用 成都機柜租用 成都服務器租用。
Java實現單鏈表反轉,遞歸和非遞歸兩種形式
/**
* 反轉單鏈表
*/
/** * 定義鏈表
*
* @author 16026
*
*/
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
public class ReverseList {
/**
* 反轉鏈表
*
* @param head
* @return
*/
public static Node reverseList(Node head) {
if (head == null || head.next == null) {
return head;
}
Node reHead = null;// 定義新鏈表頭結點
while (head != null) {
Node cur = head.next;// 記錄下一個節點
head.next = reHead;// 將rehead節點連接到head節點上
reHead = head;// 讓rehead指向head
head = cur;// 將head指向下一個節點
}
return reHead;
}
/**
* 遞歸反轉鏈表
*
* @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;// 將頭節點置于末端
head.next = null;// 防止鏈表循環
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);
}
}運行結果如下:

關于使用Java如何翻轉單鏈表就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網站欄目:使用Java如何翻轉單鏈表
網頁鏈接:http://www.yijiale78.com/article22/gipejc.html
成都網站建設公司_創新互聯,為您提供小程序開發、云服務器、標簽優化、商城網站、定制網站、定制開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯