反转一个单链表
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
import List.ListNode;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) { // 206
if(head == null || head.next == null) return head;
ListNode l1 = head;
ListNode l2 = reverseList(l1.next);
ListNode temp = l2;
while(temp.next != null) {
temp = temp.next;
}
temp.next = l1;
l1.next = null;
return l2;
}
// others
public ListNode reverseList1(ListNode head) {
if (head==null) return head;
if (head.next==null) return head;
ListNode p=reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
对比大佬的代码,我开始代码的循环多余,可改成这样
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode l2 = reverseList(head.next);
head.next.next = head;
head.next = null;
return l2;
}
}