反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
在leetcode上遇到的这个题,解题的两个方法感觉都特别巧妙
方法一:迭代
在遍历链表的时候,让当前链表的next指向前一个元素,需要事先定义一个空节点,为第一个元素指向,每次需要一个临时节点存储下一个节点。
public ListNode reverseList(ListNode head) {
ListNode p = null;
while(head != null){
ListNode temp = head.next;
head.next=p;
p=head;
head=temp;
}
return p;
}
时间复杂度 O(N)
空间复杂度 O(1)
方法二:递归
通过递归遍历到最后一个元素,然后在回退的时候,将元素倒着串起来
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
else{
ListNode p = reverseList(head.next);
head.next.next = head;
head.next=null;
return p;
}
}
时间复杂度 :O(n)
空间复杂度:O(n) 由于使用递归,需要用到隐式栈空间