写一个链表反转的java代码
时间: 2024-05-09 15:19:16 浏览: 72
以下是反转单向链表的Java代码:
```
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
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;
}
}
```
以下是反转双向链表的Java代码:
```
class ListNode {
int val;
ListNode prev;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = curr.prev;
curr.prev = temp;
if (temp == null) {
return curr;
}
curr = temp;
}
return null;
}
}
```
阅读全文