问题描述
https://leetcode.com/problems/reverse-linked-list/
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//corner case
if(head == null || head.next == null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode next = cur.next;
while(cur != null){
cur.next = pre;
pre = cur;
cur = next;
if(cur != null){
next = cur.next;
}
}
return pre;
}
}
复杂度分析
- 时间复杂度:O(1)
- 空间复杂度:O(1)