/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
// 法一:头插法
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode sentinel = new ListNode(-1);
while (head != null) {
ListNode new_head = head.next;
head.next = sentinel.next;
sentinel.next = head;
head = new_head;
}
return sentinel.next;
}
}
// 法二:递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) // 前一个判断原链表头节点是否为空,后一个判断用于递归中找到原链表尾节点(结束递归并作为新链表头节点),两种情况都是返回自身节点故合并
return head;
ListNode new_head = ReverseList(head.next); // 递归或者新链表头节点
head.next.next = head; // 反转自身节点与下一节点
head.next = null; // 自身节点的next置空,以保
NC78. 反转链表 [简单]
最新推荐文章于 2021-11-12 15:17:02 发布