206.Reverse Linked List
题目大意:翻转单链表。要求用递归和非递归两种方法。
法一:非递归。直接对原单链表进行循环操作,且不新开辟空间,用头插法即可。代码如下(耗时0ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
法二:递归。还不是很明白。代码如下(耗时1ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public ListNode reverseList(ListNode head) { 2 if(head == null || head.next == null) { 3 return head; 4 } 5 //头节点没有记录,因为头节点会成为尾结点 6 ListNode nextHead = head.next; 7 //res保证每次return的都是头结点 8 ListNode res = reverseList(head.next); 9 //return之后,开始组装结点,其实这里是尾插的思想 10 //依次会是5->4,4->3,3->2,2->1 11 nextHead.next = head; 12 //下面的这个操作不知是为啥。。。 13 head.next = null; 14 return res; 15 }