java 实现链表反转
时间: 2023-07-17 22:12:35 浏览: 121
要实现链表的反转,可以使用迭代或递归的方法。下面是使用迭代方法实现链表反转的 Java 代码示例:
```java
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class LinkedListReverse {
public ListNode reverse(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;
}
}
```
使用示例:
```java
public static void main(String[] args) {
LinkedListReverse reverser = new LinkedListReverse();
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
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);
// 反转链表
head = reverser.reverse(head);
// 打印反转后的链表
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
```
以上代码会输出:`5 4 3 2 1`,表示链表已经成功反转。
阅读全文