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

本文介绍了一种链表的反转算法实现方法,通过迭代的方式完成链表节点指向的反转,最终返回新的链表头节点。文章提供了完整的Java代码示例,并展示了如何创建链表及打印反转后的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值