以下是一個(gè)示例的Java單鏈表反轉(zhuǎn)代碼:
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class LinkedListReverse {
public static ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public static void printList(ListNode head) {
ListNode curr = head;
while (curr != null) {
System.out.print(curr.val + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode second = new ListNode(2);
ListNode third = new ListNode(3);
ListNode fourth = new ListNode(4);
head.next = second;
second.next = third;
third.next = fourth;
System.out.println("Original List:");
printList(head);
ListNode reversedHead = reverse(head);
System.out.println("Reversed List:");
printList(reversedHead);
}
}
這個(gè)示例中,我們定義了一個(gè)ListNode
類來表示鏈表中的節(jié)點(diǎn)。然后在LinkedListReverse
類中,我們實(shí)現(xiàn)了一個(gè)reverse
方法來反轉(zhuǎn)鏈表。反轉(zhuǎn)過程中,我們使用了三個(gè)指針prev
、curr
和next
,分別表示當(dāng)前節(jié)點(diǎn)的前一個(gè)節(jié)點(diǎn)、當(dāng)前節(jié)點(diǎn)和當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)。我們通過依次修改節(jié)點(diǎn)的next
指針,使得每個(gè)節(jié)點(diǎn)指向它的前一個(gè)節(jié)點(diǎn),從而實(shí)現(xiàn)鏈表的反轉(zhuǎn)。
在main
方法中,我們創(chuàng)建了一個(gè)簡單的鏈表,并調(diào)用reverse
方法來反轉(zhuǎn)鏈表。最后,我們使用printList
方法來打印反轉(zhuǎn)后的鏈表。