要實現單鏈表的反轉,可以按照以下步驟進行:
以下是用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,表示鏈表已成功反轉。