剑指Offer 24-反转链表
题目描述:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解题思路: 这道题做过很多次,还是会卡,不过这次算是彻底搞懂了,就写下来,记录一下
具体思路看图吧~
两种方法,一种递归,一种双指针。
双指针
class Solution {public ListNode reverseList(ListNode head) {// 使用双指针ListNode pre = null;ListNode cur = head;while (cur!= null){ListNode temp = cur.next;cur.next = pre;pre = cur;cur = temp;}return pre;}
}
递归
class Solution {public ListNode reverseList(ListNode head) {// 递归return reverse(head, null);}public static ListNode reverse(ListNode cur, ListNode pre){if (cur== null){return pre;}ListNode tmp = cur.next;cur.next = pre;pre = cur;cur = tmp;return reverse(cur, pre);}
}