以下是Java中鏈表反轉的示例代碼:
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class LinkedListReverse {
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
ListNode next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode reversedHead = reverseList(head);
System.out.print("Reversed List: ");
while (reversedHead != null) {
System.out.print(reversedHead.val + " ");
reversedHead = reversedHead.next;
}
}
}
運行以上代碼,將會輸出反轉后的鏈表:
Reversed List: 5 4 3 2 1
在反轉鏈表的代碼中,我們使用了三個指針prev、current和next。初始時,prev為null,current為頭節點head,next為null。在每一次循環中,我們將current的next指針指向prev,然后依次向后移動prev、current和next指針。最終,prev指針將指向反轉后的鏈表頭節點,我們將其返回即可。