反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
方法一:
通过记录前一个节点的值并通过指针不断移动的方式
时间复杂度为O(n),假设n是列表的长度,时间复杂度是O(n)
空间复杂度为O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null,cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
方法二、
通过递归的方式:
时间复杂度为O(n).假设n是列表的长度,那么时间复杂度为O(n)
空间复杂度:O(n)。由于使用递归,将会使用隐式栈空间。递归深度可能会达到n层。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode p=reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}