Java implements inputting a linked list, and after reversing the linked list, outputs all elements of the linked list.

  1. publicclass ListNode {   
  2.     int val;  
  3.     ListNode next = null;  
  4.   
  5.   
  6.     ListNode(int val) {  
  7.         this.val = val;  
  8.     }  
  9. }  
  10. publicclass Solution {   
  11. public ListNode ReverseList(ListNode head) {  
  12. if (head == null)  
  13. returnnull;   
  14. ListNode pPre =  null ;  
  15. ListNode pNext = null;  
  16. while (head != null) {  
  17. pNext = head.next;  
  18. // reverse pointer  
  19. head.next = pPre;  
  20. // pointer moves down  
  21. pPre = head;  
  22. head = pNext;  
  23. }  
  24. // The head node of the new linked list is the tail node of the original linked list  
  25. return  pPre;  
  26. }  
  27.   
  28.   
  29. void printList(ListNode last) {  
  30. while (last != null) {  
  31. System.out.print(last.val + ",");  
  32. last = last.next;  
  33.   
  34.   
  35. }  
  36.   
  37.   
  38. }  
  39.   
  40.   
  41. publicstaticvoid main(String[] args) {    
  42. ListNode head = new ListNode(1);  
  43. head.next = new ListNode(4);  
  44. head.next.next = new ListNode(3);  
  45. head.next.next.next = new ListNode(2);  
  46. Solution s =  new  Solution ();  
  47. ListNode last = s.ReverseList(head);  
  48. s.printList(last);  
  49. }  
  50. }  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776838&siteId=291194637