题目:输入一个链表,反转链表后,输出新链表的表头。
练习地址
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
方法1:遍历
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode reversedHead = null, node = head, prev = null;
while (node != null) {
ListNode next = node.next;
if (next == null) {
reversedHead = node;
}
node.next = prev;
prev = node;
node = next;
}
return reversedHead;
}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。
方法2:递归
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode reversedHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return reversedHead;
}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(n)。