题目大意:翻转单链表。要求用递归和非递归两种方法。
法一:非递归。直接对原单链表进行循环操作,且不新开辟空间,用头插法即可。代码如下(耗时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 }