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

    思路一:定义三个节点分别为当前节点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; 
    
                }
  • 相关阅读:
    js判断是否第一次访问跳转
    dt系统中tag如何使用like与%来进行模糊查询
    DT图库列表修改内容标题字数
    第二周冲刺第四天个人博客
    04《梦断代码》阅读笔记01
    第二周冲刺第三天个人博客
    03《构建之法》阅读笔记03
    第二周冲刺第二天个人博客
    02《构建之法》阅读笔记02
    第二周冲刺第一天个人博客
  • 原文地址:https://www.cnblogs.com/winAlaugh/p/5348782.html
Copyright © 2011-2022 走看看