题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
给定代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
}
}
思路
这种有关链表翻转的问题,思路基本都知道,把两个节点的指向关系调换一下。难点就是指针的迭代顺序和边界情况的处理。
题解一
迭代实现。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode left = null, right = head;
while (right != null)
{
ListNode lastRight = right.next;
right.next = left;
left = right;
right = lastRight;
}
return left;
}
}
时间复杂度:
O
(
n
)
O(n)
O(n),假设 n 是列表的长度,时间复杂度是
O
(
n
)
O(n)
O(n)。
空间复杂度:
O
(
1
)
O(1)
O(1)。
题解二
递归实现。
r e v e r s e L i s t reverseList reverseList方法作用是翻转从某个节点开始到节点末尾的整个链表。参数是一个头节点,返回值是翻转后的头节点。
所以把head.next
为首的这个链表翻转后,head.next
成了新链表的尾节点,需要做的是将尾节点的next
指为head
,并将head
的下一个变为null
。
class Solution {
public ListNode reverseList(ListNode head)
{
if (head == null || head.next == null) {
return head;
}
ListNode tmp = reverseList(head.next);
head.next.next = head;
head.next = null;
return tmp;
}
}
时间复杂度:
O
(
n
)
O(n)
O(n),假设
n
n
n 是列表的长度,那么时间复杂度为
O
(
n
)
O(n)
O(n)。
空间复杂度:
O
(
n
)
O(n)
O(n),由于使用递归,将会使用隐式栈空间。递归深度可能会达到
n
n
n 层。