• 剑指offer-从尾到头打印链表


    1.头插法,在原地遍历

    //先利用两个pre和next两个指针将头节点为cur的链表反转,
    //在依次遍历链表存储到一个ArrayList并返回
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode cur) {
            ArrayList<Integer> list=new ArrayList<Integer>();
            ListNode pre=null;
            ListNode next=null;
            while(cur!=null){
                next=cur.next;
                cur.next=pre;
                pre=cur;
                cur=next;
            }
            while(pre!=null){
                list.add(pre.val);
                pre=pre.next;
            }
            return list;
        }
    }


    反转单向链表
    
    public ListNode reverse(ListNode head){
        ListNode pre=null;
    
        while(head!=null){
             ListNode next=head.next;//记录保留当前结点的下一个结点的地址
             head.next=pre;//当前结点指针域(原为下一个结点的地址)改为上一个节点的地址
             pre=head;//上一个结点变为当前结点,为之后的循环做准备
             head=next;//当前结点变为下一个结点,为之后的循环做准备
          }
    
          return pre;
        }
    
    作者:淡茶菌
    链接:https://www.zhihu.com/question/27090581/answer/223772820
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

      

      

    链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
    来源:牛客网
    
    public class Solution {
         
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            ArrayList list=new ArrayList();
            if(listNode==null) return list;
            ListNode dummy=new ListNode(0);
            dummy.next=listNode;
            ListNode cur=listNode;
            // 链表就地反转
            while(cur.next!=null)
            {
                ListNode temp=cur.next;
                cur.next=temp.next;
                temp.next=dummy.next;
                dummy.next=temp;
            }
            ListNode head=dummy.next;
            while(head!=null)
            {
                list.add(head.val);
                head=head.next;
            } 
            return list;
             
        }
    }
  • 相关阅读:
    SOAP-ERROR: Encoding: string … is not a valid utf-8 string
    [Client] looks like we got no XML document in....
    php webservice服务端和客户端的实现
    php的soap无故出错的真凶:wsdl缓存
    php无wsdl webservice服务用法
    mysql时间运算
    PHP 操作XML文档
    YII框架安装过程-数据库访问
    【Database】MongoDB教程
    【JavaScript】HTML5存储方案
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10363153.html
Copyright © 2020-2023  润新知