Guest User

Reverse a Linked List.

a guest
May 5th, 2018
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. class ListNode{
  2.     int value;
  3.     ListNode next;
  4.     ListNode(int val){
  5.         value = val;
  6.         next = null;
  7.     }
  8. }
  9.  
  10. public class Solution{
  11.  
  12.     static ListNode makeList(int size){
  13.         ListNode head = new ListNode(1);
  14.         ListNode prev = head;
  15.  
  16.         for(int i=2;i<=size;++i){
  17.             ListNode current = new ListNode(i);
  18.             prev.next = current;
  19.             prev = current;
  20.         }  
  21.  
  22.         return head;
  23.     }
  24.  
  25.     static ListNode reverseList(ListNode head){
  26.         ListNode prev = null,current=head,next_node = null;
  27.  
  28.         while(current != null){
  29.             next_node = current.next;
  30.             current.next = prev;
  31.             prev = current;
  32.             current = next_node;
  33.         }
  34.  
  35.         return prev;
  36.     }
  37.  
  38.     static void printList(ListNode head){
  39.         System.out.println();
  40.         while(head != null){
  41.             System.out.print(head.value + "-->");
  42.             head = head.next;
  43.         }
  44.         System.out.print("NULL\n");
  45.     }
  46.  
  47.     public static void main(String[] args){
  48.         ListNode head = makeList(Integer.parseInt(args[0]));
  49.         printList(head);
  50.         head = reverseList(head);
  51.         printList(head);
  52.     }
  53. }
Add Comment
Please, Sign In to add comment