题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
方法一:迭代法
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode ReverseList (ListNode head) {
// 两个指针分别保存要反转的节点和前一个节点
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev; // prev 指向的节点就是新的头节点
}
}
方法二:递归法
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode ReverseList (ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 先反转后面的
ListNode newHead = ReverseList(head.next);
// 让后面的节点指向当前节点
head.next.next = head;
head.next = null; // 防止成环
return newHead;
}
}
老板电器公司氛围 197人发布