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;
        }
    }
  • 相关阅读:
    jQuery火箭图标返回顶部代码
    类库引用EF
    Html.DropDownList
    MVC validation
    MVC @functions
    MVC 扩展方法特点
    Class 实现IDisposing方法
    MVC两个必懂核心
    Asp.net 服务器Application,Session,Cookie,ViewState和Cache区别
    sqlserver log
  • 原文地址:https://www.cnblogs.com/newcoder/p/5796889.html
Copyright © 2011-2022 走看看