反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public ListNode reverseList(ListNode head) {
// return reverseLinkedListII(head);
// return reverseLinkedListI(head);
return reverseLinkedListIII(head, null);
}
//方法三:递归
private ListNode reverseLinkedListIII(ListNode head, ListNode newHead) {
if (head == null) return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseLinkedListIII(next, head);
}
//方法二:递归
private ListNode reverseLinkedListII(ListNode head) {
//递归终止条件
if (head == null || head.next == null) return head;
////这里的curr就是最后一个节点
ListNode curr = reverseList(head.next);
head.next.next = head;
//防止链表循环,需要将head.next设置为空
head.next = null;
////每层递归函数都返回cur,也就是最后一个节点
return curr;
}
//方法一:双指针迭代
//定义两个指针curr和prev
//遍历curr,将curr的next指向prev,同时curr和prev同时前进一位
//返回prev为头结点
private ListNode reverseLinkedListI(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}