• 剑指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;
        }
    }
    

      

  • 相关阅读:
    读《构建之法》8、9、10章有感
    评论
    复利计算器(4)——jQuery界面美化、自动补全
    送给搭档的“汉堡”
    MFC之TreeCtrl控件使用经验总结
    MFC绘制图片闪烁详解
    MFC 网络编程中::connect返回-1问题
    C++网络编程之select
    C++关于Condition Variable
    Mutex 和 Lock
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8537838.html
Copyright © 2020-2023  润新知