zoukankan      html  css  js  c++  java
  • 面试题-链表翻转

    题目

    给一个链表,进行反转

    解题思路

    每个都插头就行了

    public class Main2 {
    
    
        static class Node {
            int index;
            Node next;
    
            public Node() {
            }
    
            public Node(int index, Node next) {
                this.index = index;
                this.next = next;
            }
        }
    
    
        static Node init() {
            Node head = new Node(-1, null);
            Node tail = new Node(-1, null);
            Node temp = head;
            Node cur = head;
            for (int i = 1; i <= 100; ++i) {
                temp = new Node(i, null);
                cur.next = temp;
                cur = cur.next;
            }
            cur.next = tail;
            return head;
        }
    
        static void print(Node head) {
            System.out.print(head.index);
            while (head.next != null) {
                System.out.print(" " + head.next.index);
                head = head.next;
            }
            System.out.println();
        }
    
        static Node reverst(Node head) {
            if (head == null) {
                return null;
            }
            //初始化
            /**
             * head.next表示当前需要移到第一个位置的node,first.next表示新的链表
             */
            Node first = new Node();
            first.next = head;
            while (head.next != null) {
                Node next = head.next;
                head.next = next.next;
                next.next = first.next;
                first.next = next;
                //每次循环完,fist.next是新的表头
                // head.next表示需要移动第一个位置的node
            }
            //head.next为null,循环结束,表示已经移动完
            Node result = first.next;
            first.next = null;
            return result;
        }
    
    
        public static void main(String args[]) {
            Node head = init();
            print(head);
            head = reverst(head);
            print(head);
        }
    }
    
    

    证明

    初始化

    head.next表示当前需要移到第一个位置的node,first.next表示新的链表

    循环

    每次循环完,head.next表示还是当前移到第一个位置的node,first.next还是表示新的链表

    结束

    head.next为null,循环结束,表示已经移动完

  • 相关阅读:
    超文本传输协议 HTTP/1.0 Hyptertext Transfer Protocol
    VB.NET中使用代表对方法异步调用
    蚂蚁解道德经(1)[转载]
    vb.net 类的属性的设置和获取问题
    VB.net入门(6):类~构造函数,事件
    什么是Ajax技术
    千里之外
    一个asp.net2005的页面文件调用CSS样式的BUG
    一个.net发送HTTP数据实体的类
    利用ASP发送和接收XML数据的处理方法
  • 原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/14579977.html
Copyright © 2011-2022 走看看