共計 929 個字符,預計需要花費 3 分鐘才能閱讀完成。
要實現單鏈表的反轉,可以按照以下步驟進行:
- 創建一個新的鏈表,作為反轉后的鏈表。
- 遍歷原鏈表,將每個節點插入到新鏈表的頭部。
- 返回新鏈表作為反轉后的鏈表。
以下是用 Java 實現單鏈表反轉的示例代碼:
class ListNode {int val;
ListNode next;
ListNode(int val) {this.val = val;
this.next = null;
}
}
public class LinkedListReverse {public static ListNode reverse(ListNode head) {ListNode newHead = null;
while (head != null) {ListNode nextNode = head.next;
head.next = newHead;
newHead = head;
head = nextNode;
}
return newHead;
}
public static void main(String[] args) {// 創建一個示例鏈表 1->2->3->4->5
ListNode head = new ListNode(1);
ListNode second = new ListNode(2);
ListNode third = new ListNode(3);
ListNode fourth = new ListNode(4);
ListNode fifth = new ListNode(5);
head.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
// 反轉鏈表
ListNode newHead = reverse(head);
// 打印反轉后的鏈表值
ListNode currentNode = newHead;
while (currentNode != null) {System.out.print(currentNode.val + " ");
currentNode = currentNode.next;
}
// 輸出結果: 5 4 3 2 1
}
}
在上述示例代碼中,我們創建了一個單鏈表,并使用 reverse
方法將其反轉。最后,我們遍歷反轉后的鏈表,并打印每個節點的值。輸出結果為 5 4 3 2 1,表示鏈表已成功反轉。
丸趣 TV 網 – 提供最優質的資源集合!
正文完