0
点赞
收藏
分享

微信扫一扫

LeetCode练习7:反转链表

程序员伟杰 2022-03-15 阅读 55

LeetCode链接:力扣

题目:

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

 代码一:(双指针法)时间复杂度O(n),空间复杂度O(1)     如果是新定义链表来存储的话,时间复杂度就变成O(n^2)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode tmp;   //临时存放节点
        ListNode cur = head, pre = null;
        while(cur != null){
            tmp = cur.next;
            cur.next = pre;         //反转链表,将cur.next指向pre
            pre = cur;              //移动pre指针指向的位置
            cur = tmp;              //移动tmp指针指向的位置
        }
        return pre;
    }
}

代码二:(递归方法) 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // ListNode tmp;   //临时存放节点
        // ListNode cur = head, pre = null;
        // while(cur != null){
        //     tmp = cur.next;
        //     cur.next = pre;         //反转链表,将cur.next指向pre
        //     pre = cur;              //移动pre指针指向的位置
        //     cur = tmp;              //移动tmp指针指向的位置
        // }
        // return pre;
        return reverse(null, head);
    }

    public ListNode reverse(ListNode pre, ListNode cur){
        if(cur == null) return pre;
        ListNode tmp = cur.next;
        cur.next = pre;
        return reverse(cur, tmp);
    }
}
举报

相关推荐

0 条评论