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;
            
        }
    }
    
  • 相关阅读:
    不要为自己找借口,你可以做到的--职场实用做人法则
    sql server 利用发布订阅方式实现数据库同步问题
    关于免费空间的寻找
    数据自定义格式化
    C++字符串string类常用操作详解(一)【初始化、遍历、连接】
    C++ 命名空间
    gcc/g++ 如何支持c11 / c++11标准编译
    正确的C++/C堆栈
    linux下清空c++ cin无效流的方式
    32位64位下各种数据类型大小的对比
  • 原文地址:https://www.cnblogs.com/qwer112/p/13932859.html
Copyright © 2011-2022 走看看