题目链接

题目大意:翻转单链表。要求用递归和非递归两种方法。

法一:非递归。直接对原单链表进行循环操作,且不新开辟空间,用头插法即可。代码如下(耗时0ms):

 1     public ListNode reverseList(ListNode head) {
 2         if(head == null) {
 3             return head;
 4         }
 5         ListNode res = head;
 6         head = head.next;
 7         res.next = null;
 8         while(head != null) {
 9             ListNode tmp = head;
10             //head=head.next一定要放在tmp.next=res的前面
11             //因为如果放在后面,tmp.next=res就会改变head.next的值,这样head就不能正常指向原值,会造成死循环
12             head = head.next;
13             //下面是头插法
14             tmp.next = res;
15             res = tmp;
16         }
17         return res;
18     }
View Code

相关文章:

  • 2021-12-06
  • 2021-08-30
  • 2021-08-20
  • 2021-10-13
  • 2021-12-16
  • 2021-07-21
  • 2021-06-24
  • 2021-12-15
猜你喜欢
  • 2021-11-23
  • 2021-06-13
相关资源
相似解决方案