英文链接:https://leetcode.com/problems/reverse-linked-list/
中文链接:https://leetcode-cn.com/problems/reverse-linked-list/
题目详述
反转一个单链表。
示例:
1 2
|
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
|
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
题目详解
解决这种问题免不了对结点的 next 进行操作,最好的方式是先用纸笔画图模拟一下操作过程,再来写代码。
下面是迭代版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class {
public ListNode reverseList(ListNode head) { ListNode cur = head; ListNode pre = null; while (cur != null) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
|
下面是递归版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public class {
public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; } }
|
近期评论