zoukankan      html  css  js  c++  java
  • 面试题 16:反转链表

    面试题 16:反转链表

    题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的 头结点。

    用三个指针,pre,now,next

    注意用例:

    空链表;

    链表只有一个结点。

    package offer;
    /*题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的 头结点。*/
    public class Problem16 {
        static class ListNode{
            int data;
            ListNode nextNode;
        }
        public static void main(String[] args) {
            ListNode head = new ListNode();
            ListNode second = new ListNode();
            ListNode third = new ListNode();
            ListNode forth = new ListNode();
            head.nextNode = second;
            second.nextNode = third;
            third.nextNode = forth;
            head.data = 1;
            second.data = 2;
            third.data = 3;
            forth.data = 4;
            Problem16 test = new Problem16();
            ListNode resultListNode = test.reverseList(head);
            System.out.println(resultListNode.data);
        }
    
        public ListNode reverseList(ListNode head) {
            if (head == null) {
                return null;
            }
            //只有一个结点
            if (head.nextNode == null) {
                return head;
            }
            ListNode preListNode = null;
            ListNode nowListNode = head;
            ListNode reversedHead = null;
            //注意循环结束条件
            while (nowListNode.nextNode != null) {
                ListNode nextListNode = nowListNode.nextNode;
                if (nextListNode == null)
                    reversedHead = nextListNode;
                nowListNode.nextNode = preListNode;
                preListNode = nowListNode;
                nowListNode = nextListNode;
            }
            return nowListNode;
        }
    }
  • 相关阅读:
    彻底理解Netty
    linux netstat 统计连接数查看
    log4j2 自动删除过期日志文件配置及实现原理解析
    Log4j2的Policy触发策略与Strategy滚动策略配置详解
    @Accessors
    Caffeine Cache实战
    ws协议与http协议的异同
    深入理解Java:注解(Annotation)自定义注解入门
    java日志框架
    springboot 集成J2Cache
  • 原文地址:https://www.cnblogs.com/newcoder/p/5796889.html
Copyright © 2011-2022 走看看