zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第二章 链表问题 反转单向链表和双向链表

    题目

    反转单向链表和双向链表
    

    java代码

    /**
     * @Description:反转单向链表和双向链表
     * @Author: lizhouwei
     * @CreateDate: 2018/4/6 11:07
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter2_4 {
        //反转单向链表
        public Node reverse(Node head){
            if(head ==null){
                return null;
            }
             Node pre = null;
            Node next=null;
            while (head!=null){
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            return  pre;
        }
    
        //反转双向链表
        public DoubleNode reverseDNode(DoubleNode head){
            if(head ==null){
                return null;
            }
            DoubleNode pre = null;
            DoubleNode next=null;
            while (head!=null){
                next = head.next;
                head.next = pre;
                head.pre = next;
                pre = head;
                head = next;
            }
            return  pre;
        }
        public void printLink(Node head) {
            System.out.println();
            while (head != null) {
                System.out.print(head.vlaue + " ");
                head = head.next;
            }
        }
    
        public void printDLink(DoubleNode head) {
            System.out.println();
            while (head != null) {
                System.out.print(head.vlaue + " ");
                head = head.next;
            }
        }
    
        //测试
        public static void main(String[] args) {
            Chapter2_4 chapter = new Chapter2_4();
            Link link1 = new Link();//单链表
            Link link2 = new Link();//双链表
    
            //构造链表
            for (int i = 10; i > 0; i--) {
                link1.add(i);
                link2.addDoubleNode(i);
            }
            chapter.printLink(link1.head);
            Node head = chapter.reverse(link1.head);
            chapter.printLink(head);
            chapter.printDLink(link2.dhead);
            DoubleNode dhead = chapter.reverseDNode(link2.dhead);
            chapter.printDLink(dhead);
    
        }
    }
    
  • 相关阅读:
    MyEclipse的使用
    监控linux各主机系统时间是否一致
    Myeclipse反编译工具
    Myeclipse添加源码链接
    ORA-32004: obsolete or deprecated parameter(s) specified for RDBMS instance
    Authentication token manipulation error报错解决办法
    大数据项目
    maxcompute笔记
    kfrobotaidlog查找
    2019.02.12-2019.02.19 工作安排
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8727222.html
Copyright © 2011-2022 走看看