leetcode每日一题之反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
解法1:迭代法
思路:首先定义两个指针prev和curr分别指向null和head,然后将curr.next=prev,但是这样的话就断开了链条,因此还需要一个指针next保存下一个节点,每次执行next=curr.next,curr.next=prev,prev=curr;curr=next;也即是每次向后同时移动curr和prev,然后用next每次记录下一个节点
代码:
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
解法2:递归
递归的解法比较难懂,研究了一下午找到一个比较通俗易懂的动画演示:
题解链接(有动画演示递归过程):https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/dong-hua-yan-shi-duo-chong-jie-fa-206-fan-zhuan-li/
直接上代码:
class Solution {
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;
}
}
结合上面链接看吧!