每日一练leetcode

Offer 24. 反转链表

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

此题和之前做的题不同点是一个最后按照数组输出 一个是按照链表头结点输出其实方法是一样的 我再做一遍额目的是加深熟练程度,还有做链表题一定要先画图再去写代码!

方法一 双指针法(yyds)

定义两个指针: pre 和 cur ;pre在前 cur 在后。
每次让 pre 的 next指向 cur ,实现一次局部反转
局部反转完成之后, pre 和 cur同时往前移动一个位置
循环上述过程,直至 pre 到达链表尾部

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
       ListNode cur = head, pre = null;
       while(cur != null){
           ListNode tmp = cur.next;
           cur.next = pre;
           pre = cur;
           cur = tmp;
       }
       return pre;
    }
}

 方法二 递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    public ListNode reverseList(ListNode head) {
        return recur(head, null);    // 调用递归并返回
    }
    private ListNode recur(ListNode cur, ListNode pre) {
        if (cur == null) return pre; // 终止条件
        ListNode res = recur(cur.next, cur);  // 递归后继节点
        cur.next = pre;              // 修改节点引用指向
        return res;                  // 返回反转链表的头节点
    }
}

  

原文地址:https://www.cnblogs.com/nenu/p/15069298.html