• 反转单向链表


    思路一:定义三个节点分别为当前节点cur,前一个节点pre,后一个节点next
    我们需要当前节点由指向next转变为指向pre,并且我们必须先将下一个节点缓存起来否则改变了当前节点的指向
    我们无法继续遍历整个链表了。
    即步骤如下
    1 缓存当前节点的下一个节点 next=cur.next;
    2 将当前节点指向前一个节点 cur.next=pre;
    3 前一个节点后移一位,指向当前节点;pre=cur;
    4 当前节点后移一位 cur=next;
     
      public ListNode ReverseList(ListNode head) {
    
        ListNode cur = head;
    
        ListNode pre = null;
    
        ListNode next = null;
    
        while (cur != null) {
    
            next = cur.next;
    
            cur.next = pre;
    
            pre = cur;
    
            cur = next;
    
        }
    
        return pre;
    
        }
    思路二:借助于栈结构,首先遍历链表并且存储于栈中,接着 根据弹栈的顺序重新遍历栈并且更改每个
    节点的值  当然,在这里是通过改变每个节点的值来达到效果的 并没有 改变节点的 引用关系
     
     public ListNode ReverseList(ListNode head) {
    
        ListNode cur = head;
    
                ListNode pre = head;
    
                ListNode next = null;
    
               //借助栈的数据结构
    
                Stack stack = new Stack();
    
                while(cur!=null){
    
                    stack.push(cur.val);
    
                    cur=cur.next;
    
                }
    
                while(!stack.isEmpty()){
    
                    pre.val=(int) stack.pop();
    
                    pre=pre.next;
    
                }
    
                return head;
    
        }
    思路三 采用递归实现
    public ListNode ReverseList(ListNode head) {
    
            if (null == head || null == head.next) {  
    
              return head;  
    
                 }  
    
            ListNode reversedHead = ReverseList(head.next);  
    
            head.next.next=head;  
    
            head.next=null; 
    
            return reversedHead; 
    
                }
  • 相关阅读:
    流程配置中心选不到销售订单新变更单
    python中判断NULL
    BOS的长度范围(字符)
    业务对象功能授权无法找到用户权限申请单
    116环境无法上传附件
    审批流XML的岗位存储的值
    solidity语法4——合约(类似面向对象中的Class)
    solidity语法3——全局变量,表达式,控制结构
    solidity语法1——概述
    solidity语法2——类型
  • 原文地址:https://www.cnblogs.com/winAlaugh/p/5348782.html
Copyright © 2020-2023  润新知