zoukankan      html  css  js  c++  java
  • 206. 反转链表

    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    package p206;
    
    /**
     * Created by admin on 2019/1/10.
     */
    public class Main {
    
        public static class Node{
            public int value;
            public Node next;
            public Node(int data){
                this.value = data;
            }
        }
    
        public static void main(String[] args) {
            Node node1 = new Node(1);
            Node node2 = new Node(2);
            Node node3 = new Node(3);
            Node node4 = new Node(4);
            Node node5 = new Node(5);
            node1.next = node2;
            node2.next = node3;
            node3.next = node4;
            node4.next = node5;
            node5.next = null;
    
            Main m = new Main();
            Node node = m.reverseList2(node1);
            Node current = node;
            System.out.println(current.value);
    
        }
    
        public Node reverseList(Node head){
            Node pre = null;
            Node next = null;
            while (head != null) {
                next = head.next;
                head.next = null;
                pre = head;
                head = next;
            }
            return pre;
        }
    
        public Node reverseList2(Node head){
            if (head == null || head.next == null) {
                return head;
            }
            Node pre = null;
            while (head != null) {
                Node temp = head.next;
                head.next = pre;
                pre = head;
                head = temp;
            }
    
            return pre;
        }
    
    }
    

      

  • 相关阅读:
    JQuery判断checkbox是否选中-批量
    浮动跟随
    当天时间戳范围
    统计兼职人员打标签数量
    submit回车提交影响
    js 数组去除空值
    js循环
    ajax
    滚动条位置
    oc基础-set和get方法的使用
  • 原文地址:https://www.cnblogs.com/airycode/p/10250866.html
Copyright © 2011-2022 走看看