class Solution { public ListNode reverseList(ListNode head) { ListNode cur = head, prev = null, next = null; while (cur != null) { next = cur.next; cur.next = prev;
// shift to next node prev = cur; cur = next; } return prev; } }
// Recursive class Solution { public ListNode reverseList(ListNode head) { return reverseRec(head, null); } private ListNode reverseRec(ListNode head, ListNode newHead) { if (head == null) return newHead; ListNode next = head.next; head.next = newHead; return reverseRec(next, head); } }
# T:O(n), S:O:(1) # Definition for singly-linked list. # class ListNode: # def init(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, curr = None, head # end, start while curr != None: curr.next, prev, curr = prev, curr, curr.next # reverse curr and prev, curr go next return prev # recursive version class Solution: def reverseList(self, head): if head is None or head.next is None: return head result = self.reverseList(head.next) # go through head.next.next,head.next = head,None # reverse return result