java实现输入一个链表,反转链表后,输出链表的所有元素。

  1. public class ListNode {  
  2.     int val;  
  3.     ListNode next = null;  
  4.   
  5.   
  6.     ListNode(int val) {  
  7.         this.val = val;  
  8.     }  
  9. }  
  10. public class Solution {  
  11. public ListNode ReverseList(ListNode head) {  
  12. if (head == null)  
  13. return null;  
  14. ListNode pPre = null;  
  15. ListNode pNext = null;  
  16. while (head != null) {  
  17. pNext = head.next;  
  18. // 反转指向  
  19. head.next = pPre;  
  20. // 指针往下移动  
  21. pPre = head;  
  22. head = pNext;  
  23. }  
  24. // 新链表的头结点就是原链表的尾结点  
  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. public static void 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. }  

猜你喜欢

转载自blog.csdn.net/qq_36838191/article/details/80209883