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;
        }
    }
  • 相关阅读:
    no space left on device
    功能测试用例
    数据库命令
    移动APP测试用例设计实践经验(转载)
    15个常用sql命令
    将Windows文件夹挂载到Linux上
    英语学习方法
    三种特质 做领导
    扬州之行 第一天
    list、dict、str虽然是Iterable,却不是Iterator
  • 原文地址:https://www.cnblogs.com/newcoder/p/5796889.html
Copyright © 2011-2022 走看看