zoukankan      html  css  js  c++  java
  • Java 链表反转

    链表数据结构如下:

    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */ 

    给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

    反转链表思路:将当前链表放入stack 利用stack的特性LIFO做反转,需要注意的是stack中最后一个元素时需要讲next节点设置为null,否则后指向原始链表的第二个节点,

    代码如下

    public class Solution {
        /**
         * @param head: The head of linked list.
         * @return: The new head of reversed linked list.
         */
        public ListNode reverse(ListNode head) {
            if(head==null){
                return null;
            }
            Stack<ListNode> stack = new Stack<>();
    
            while(head!=null){
                stack.push(head);//链表元素入栈
                head=head.next;
            }
    
            ListNode current =stack.pop(); //获得头节点
            ListNode root = current;
            while (!stack.isEmpty()){
            ListNode next = stack.pop();
    
                //最后一个元素时处理next为null
                if(stack.size()==0){
                    next.next=null;
                    current.next=next;
                }else{
                    current.next=next;
                    current=next;
                }
    
            }
    
            return root;
        }
    }
  • 相关阅读:
    t
    溢出
    https://stackoverflow.com/questions/45591594/fetch-does-not-send-headers
    显示在用户屏幕上的缩略图
    cache buffer
    LZW
    t
    指针悬挂
    使用Linux服务器来通过网络安装和激活Windows 7 —— 一些基本原理
    在C++中如何动态分配一个二维数组
  • 原文地址:https://www.cnblogs.com/lilefordream/p/7084413.html
Copyright © 2011-2022 走看看