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

    反转链表

    题目描述

    输入一个链表,反转链表后,输出新链表的表头。

    题目链接: 反转链表

    代码

    /**
     * 标题:反转链表
     * 题目描述
     * 输入一个链表,反转链表后,输出新链表的表头。
     * 题目链接:
     * https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&&tqId=11168&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
     */
    public class Jz15 {
    
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode first = head, second = head.next;
            first.next = null;
            while (first != null && second != null) {
                ListNode temp = first;
                first = second;
                second = second.next;
                first.next = temp;
            }
            return first;
        }
    
        public static void main(String[] args) {
            ListNode head = new ListNode(1);
            head.next = new ListNode(2);
            head.next.next = new ListNode(3);
            System.out.println("before reverse");
            ListNode cur = head;
            while (cur != null) {
                System.out.print(cur.val + " ");
                cur = cur.next;
            }
            System.out.println();
            Jz15 jz15 = new Jz15();
            ListNode result = jz15.reverseList(head);
            System.out.println("after reverse");
            ListNode cur1 = result;
            while (cur1 != null) {
                System.out.print(cur1.val + " ");
                cur1 = cur1.next;
            }
        }
    }
    

    【每日寄语】 生活的本质就是幸福的活着,而生活的智慧就是活出自己想要的样子。

  • 相关阅读:
    Json对象和字符串互转
    JSNOP调用。。。
    org.hibernate.LazyInitializationException: could not initialize proxy no Session
    myeclipse生成注解实体
    jquery判断浏览器和版本
    JSTL XML标签库
    ORACLE 月份不全,补全月份的sql
    js 上下左右键控制焦点
    google gson使用
    js判断undefined类型
  • 原文地址:https://www.cnblogs.com/kaesar/p/15640961.html
Copyright © 2011-2022 走看看