题目链接:https://leetcode.cn/problems/reverse-linked-list/description/?envType=study-plan-v2&envId=top-100-liked
迭代
1 -> 2 - > 3 -> null 变成 null <- 1 <- 2 <- 3
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//存储前一个节点
ListNode pre = null;
//存储当前节点
ListNode cur = head;
while(cur != null){
//存储下一个节点
ListNode next = cur.next;
//下一个节点换成上一个节点
cur.next = pre;
//上一个节点换成当前节点
pre = cur;
//当前节点换成下一个节点
cur = next;
}
return pre;
}
}
修改节点指向
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode ans = null;
//遍历每个节点
for(ListNode i = head; i != null; i = i.next){
//把下一个节点换成上一个节点
ans = new ListNode(i.val, ans);
}
return ans;
}
}
递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//防止递归进去空节点
if(head == null || head.next == null){
return head;
}
//递归下一个节点
ListNode ans = reverseList(head.next);
//下一个节点指向当前节点
head.next.next = head;
//当前节点指向空节点
head.next = null;
return ans;
}
}
还剩87题!