/**
 * class ListNode {
 *   public int value;
 *   public ListNode next;
 *   public ListNode(int value) {
 *     this.value = value;
 *     next = null;
 *   }
 * }
 */
public class Solution {

  public ListNode reverse(ListNode head) {
    // write your solution here
    if (head == null || head.next == null) {
      return head;
    }
    ListNode prev = null;
    ListNode nextNode = null;
    ListNode cur = head;
    while(cur != null) {
      nextNode = cur.next;
      cur.next = prev;
      prev = cur;
      cur = nextNode;
    }
    return prev;
  }

//Recursive way:
//   public ListNode reverse(ListNode head) {
//     if (head == null || head.next == null) {
//       return head;
//     }
//     ListNode newHead = reverse(head.next);
//     head.next.next = head;
//     head.next = null;
//     return newHead;
//   }
}

results matching ""

    No results matching ""