fork download
  1. var head;
  2.  
  3. class Node { constructor(val) {
  4. this.data = val; this.next = null;
  5. } }
  6. /* Function to reverse the linked list */
  7. function reverseLinkedList(node) {
  8. var prev = null;
  9. var current = node;
  10. var next = null;
  11. while (current != null) {
  12. next = current.next;
  13. current.next = prev;
  14. prev = current;
  15. current = next;
  16. }
  17. node = prev;
  18. return node;
  19. }
  20.  
  21.  
  22. function printList(node) {
  23. while (node != null) {
  24. console.log(node.data + " ");
  25. node = node.next;
  26.  
  27. } }
  28.  
  29.  
  30.  
  31. // Driver Code
  32. const n = parseInt(readline());
  33. const inp = parseInt(readline());
  34. if(n>0){
  35. head = new Node(inp[0]);
  36. }
  37. else{
  38. console.log("");
  39. }
  40. let temp=head;
  41. for(let i=1;i<n;i++){
  42. temp.next=new Node(inp[i]);
  43. temp=temp.next;
  44.  
  45. }
  46.  
  47. printList(head);
  48. head = reverseLinkedList(head);
  49.  
  50. printList(head);
Success #stdin #stdout 0.04s 16432KB
stdin
5
1,2,3,4,5
stdout
undefined 
undefined 
undefined 
undefined 
undefined 
undefined 
undefined 
undefined 
undefined 
undefined