Skip to content

Instantly share code, notes, and snippets.

@El-Sam
Created October 11, 2017 22:59
Show Gist options
  • Select an option

  • Save El-Sam/1d2078c28916e8e44a0dfc9064655f1c to your computer and use it in GitHub Desktop.

Select an option

Save El-Sam/1d2078c28916e8e44a0dfc9064655f1c to your computer and use it in GitHub Desktop.

Revisions

  1. El-Sam revised this gist Oct 11, 2017. No changes.
  2. El-Sam created this gist Oct 11, 2017.
    26 changes: 26 additions & 0 deletions ReverseLinkedList.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    /*
    Reverse a linked list and return pointer to the head
    The input list will have at least one element
    Node is defined as
    class Node {
    int data;
    Node next;
    }
    */

    Node Reverse(Node head) {
    if(head == null || head.next == null)
    return head;

    Node p = null;
    Node tail= null;

    while(head != null){
    p = head.next;
    head.next = tail;
    tail = head;
    head = p;
    }

    return tail;
    }