public class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
}
//递归反转链表 时间复杂度为O(n); 空间复杂度为O(n);
public reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode temp = head.next;
ListNode newHead = reverse(temp);
temp.next = head;
head.next = null;
return newHead;
}
//迭代反转链表,时间复杂度为O(n); 空间复杂度为O(1);
class Solution{
public ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode nexttemp = cur.next;
cur.next = prev;
prev = cur;
cur = nexttemp;
}
return prev;
}
}