1.4 Reverse Linked List

Description

Reverse a singly linked list.

Method

Three pointers to reverse each node one by one.

Time and Space Complexity

o(n)

Code

public class Solution {

public ListNode reverseList(ListNode head) {
       if (head == null || head.next == null){
           return head;
       }
       ListNode pre = head;
       ListNode cur = head;
       ListNode post = null;

       while (cur != null){
             pre = cur.next;
             cur.next = post;
             post = cur;
             cur = pre;
       }
       return post;
}

}

results matching ""

    No results matching ""