206.反转链表Java

2021/6/20 22:26:46

本文主要是介绍206.反转链表Java,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

206.反转链表Java

题目描述

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

输入输出样式

示例1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
在这里插入图片描述

示例2:
输入:head = [1,2]
输出:[2,1]

在这里插入图片描述

本文题来自LeetCode:https://leetcode-cn.com/problems/reverse-linked-list/

思路

方法一:新创建一个头结点,遍历需要反转的链表,一个一个节点用头插法,插入新的头结点后,反转即完成。
方法二:用栈先进后出的性质。把链表的节点压入栈中,再依次出栈就是反转后的结果
方法三:迭代。方法1,2都需要开辟空间。而我们想办法只要把链表从左往右的方向调转为从右往左就不需要新的空间。利用双指针扫描链表,依次调转节点的指向。
方法四:递归,假设链表:head->a->b->…核心思想为:head.next.next = head。那么就有a->head,同时head.next = null;就有a->head->null;

算法分析

方法一:时间复杂度O(n),空间复杂度为O(n)
方法二:时间复杂度O(n),空间复杂度为O(n)
方法三:时间复杂度O(n),空间复杂度为O(1)
方法四:时间复杂度O(n),空间复杂度为O(n)

求解函数

/**
 * 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) {
        if (head == null || head.next == null) return head;
        ListNode newHead = new ListNode();
        ListNode cur = head;
        while (cur != null) {
            ListNode temp = new ListNode(cur.val, newHead.next);
            //头插法
            newHead.next = temp;
            cur = cur.next;
        }
        return newHead.next;
    }
}
class Solution {
	//方法二:栈
    public ListNode reverseList(ListNode head) {
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode cur = head, s;
        ListNode newHead = new ListNode();
        s = newHead;
        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        while (!stack.isEmpty()) {
            ListNode temp = stack.pop();
            temp.next = null;
            //尾插法
            s.next = temp;
            s = temp;
        }
        return newHead.next;
    } 
}
class Solution {
	//方法三:迭代
    public ListNode reverseList(ListNode head) {
        ListNode cur = head, prev = null;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}
class Solution {
	//方法四:递归
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode p = reverseList(head.next); //保存反转后返回的
        //核心思想
        head.next.next = head;
        head.next = null;
        return p;
    } 
}


这篇关于206.反转链表Java的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程