Java实现单链表反转
时间: 2023-03-29 10:03:17 浏览: 137
可以使用迭代或递归的方式实现单链表反转。以下是迭代方式的代码示例:
```java
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
```
其中,ListNode 是单链表节点的定义,包含一个 val 属性和一个 next 属性,表示节点的值和下一个节点的指针。
相关问题
如何用java实现单链表逆转
在Java中,可以使用迭代的方式来实现单链表的逆转,下面是一个简单的示例:
```java
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode reverseList(ListNode head) {
// 初始化两个指针,prev为null,current为head
ListNode prev = null, current = head;
// 当current不为null时,循环遍历并反转链表
while (current != null) {
// 记录当前节点的下一个节点
ListNode nextTemp = current.next;
// 更新当前节点的next指向prev
current.next = prev;
// 移动prev和current指针
prev = current;
current = nextTemp;
}
// 返回新头节点,即原链表的尾部
return prev;
}
}
```
在这个例子中,我们通过修改节点的`next`指针,实现了链表节点顺序的反转。首先将`current.next`指向`prev`,然后将`prev`和`current`向前移动一位,直到`current`变为`null`。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)