要实现单链表的反转,可以按照以下步骤进行:
以下是用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,表示链表已成功反转。