zoukankan      html  css  js  c++  java
  • 剑指offer——反转链表

    反转链表

    输入一个链表,反转链表后,输出链表的所有元素。

    在这里注意:

    在反转的链表最后,有一个操作:

    在stack中第一个压入的结点的next是指向第二个结点的,在最后要改成null,才能改成最后一个结点

    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    import java.util.Stack;
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null || head.next == null) return head;
            Stack<ListNode> st = new Stack<>();
            while(head != null){
                st.push(head);
                head = head.next;
            }
            ListNode node = st.pop();
            ListNode reHead = node;
            while(!st.empty()){
                node.next = st.pop();
                node = node.next;
            }
            node.next = null;
            return reHead;
        }
    }
    

      

    别人的思路

    就是定义一个前驱结点preNode,一个后继结点pNext

    pNext = pNode.next;(记录当前节点的下一个结点)

    pNode.next = preNode;(将当前节点的下一个结点指向前驱节点)

    preNode = pNode;(将前驱节点指向当前节点)

    pNode = pNext;(当前节点指向下一个结点)

    循环即可

    当pNext == null时,节点达到链表尾部,此时将newHead = pNode;即可得到新链表的头部

    /*
    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;
            ListNode newHead = null;
            ListNode pNode = head;
            ListNode preNode = null;
            while(pNode != null){
                ListNode pNext = pNode.next;
                if(pNext == null) newHead = pNode;
                pNode.next = preNode;
                preNode = pNode;
                pNode = pNext;
            }
            return newHead;
        }
    }
    

      

  • 相关阅读:
    java中通过jacob调用dts进行数据导入导出
    Tomcat6 配置快逸报表
    [转]Sql Server Alter语句
    redhat linux卸载自带的Java1.4.2安装JDK6
    住房公积金额度计算
    JVisualVM使用
    Tomcat假死之问题原因排查
    JVM内存调优之监控篇
    tomcat之JVM GC 日志文件生成
    webstorm8的license
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8537838.html
Copyright © 2011-2022 走看看