//递归实现
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return head;
ListNode res = reverse(head);
return res;
}
public ListNode reverse(ListNode head){
if(head.next == null) return head;
ListNode node = reverse(head.next);
head.next.next = head;
head.next = null;
return node;
}
}
//非递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return head;
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode node = cur.next;
cur.next = pre;
pre = cur;
cur = node;
}
return pre;
}
}
剑指offer 24 反转链表,递归非递归
最新推荐文章于 2021-11-17 20:56:28 发布