1.反转单向链表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ac6923d34f65676babc38454c150a933.png)
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
public static Node reverseList(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
leetcode 92 题:反转从位置 m 到 n 的链表
public class LC92 {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode res = new ListNode(0);
res.next = head;
ListNode node = res;
for (int i = 0; i < m - 1; i++) {
node = node.next;
}
ListNode start = node.next;
ListNode pre = null;
ListNode next = null;
for (int i = 0; i <= n - m; i++) {
next = start.next;
start.next = pre;
pre = start;
start = next;
}
node.next = pre;
while (pre.next != null) {
pre = pre.next;
}
pre.next = next;
return res.next;
}
}
2.反转双向链表
- 与上面反转单链表的代码只有两处不同:①定义结点时加入last指针;②添加 head.last = next
public static class DoubleNode {
public int value;
public DoubleNode next;
public DoubleNode last;
public DoubleNode(int data) {
this.value = data;
}
}
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}