zoukankan      html  css  js  c++  java
  • 牛客题霸反转链表题解

    反转链表

    牛客题霸NC78

    难度:Easy

    题目描述:

    输入一个链表,反转链表后,输出新链表的表头。

    示例:

    输入:
    {1, 2, 3}
    输出:
    {3, 2, 1}
    

    解决方法:

    1.通过栈+尾插法实现

    可以将所有节点入栈,然后逐个出栈,插入到链表尾部。

    import java.util.*;
    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            
            Stack<ListNode> stack = new Stack<>();
            while(head != null){
                stack.push(head);
                head = head.next;
            }
            
            ListNode newHead = null;
            ListNode tail = null;
            while(!stack.isEmpty()){
                ListNode node = stack.pop();
                node.next = null;
                if(newHead == null){
                    newHead = node;
                    tail = node;
                }
                else{
                    tail.next = node;
                    tail = node;
                }
                
            }
            
            return newHead;
        }
    }
    
    2.头插法

    我们要将链表逆序,可以遍历原链表,对每个节点采用头插法插入到新链表中即可实现反转。

    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            
            ListNode newHead = null;
            
            while(head != null){
                ListNode nextNode = head.next;
                head.next = newHead;
                newHead = head;
                head = nextNode;
            }
            
            return newHead;
            
        }
    }
    
    3.通过递归实现

    递归也可以实现链表反转,但是效率比较低。

    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            // 一个或者没有节点直接返回
            if(head == null || head.next == null){
                return head;
            }
            // 反转head.next为开始的链表
            ListNode newHead = ReverseList(head.next);
            // 将head节点放到链表尾部
            head.next.next = head;
            head.next = null;
            
            return newHead;
            
        }
    }
    
  • 相关阅读:
    HASH算法介绍
    windowsOracle19C安装
    Oracle快照控制文件理解
    Swap空间扩展
    OracleDBA职责—备份与恢复技术—RMAN4
    OI回忆录
    HEOI2020(NEW)
    HEOI2020
    省选前奇怪的心情减少了
    $Mom$
  • 原文地址:https://www.cnblogs.com/qwer112/p/13932859.html
Copyright © 2011-2022 走看看