zoukankan      html  css  js  c++  java
  • Reverse Linked List II——LeetCode

    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    题目大意就是给一个单链表,给定一个起点和一个终点,反转起点和终点之间的链表,要求:原地反转,一次遍历。

    解题思路:因为已经限制了1 ≤ m ≤ n ≤ length of list,设定头节点指向第一个元素,工作指针先走m步,采用头插法来重新构建m到n之间的数据,最后把m位置上的next指针指向原来的n+1的位置。

    这次代码写的有点纠结,Java操作这些不如c++熟练。

    public ListNode reverseBetween(ListNode head, int m, int n) {
            if (head == null || m == n) {
                return head;
            }
            int count = n - m;
            ListNode p = new ListNode(0);
            ListNode q;
            ListNode headp = new ListNode(0);
            ListNode res = headp;
            p.next = head;
            headp.next = head;
            while (--m > 0) {
                headp = headp.next;
            }
            p = headp.next;
            q = p.next;
            ListNode last = p;
            headp.next = null;
            while (count-- >= 0) {
                p.next = headp.next;
                headp.next = p;
                if (q != null) {
                    p = q;
                    q = q.next;
                } else {
                    p = null;
                }
            }
            last.next = p;
            /*while(res!=null){
                System.out.println(res.val);
                res=res.next;
            }*/
            return res.next;
        }
  • 相关阅读:
    第一次做的破网页
    c++初学指针
    eskibana
    有关JSON以及JSON在PHP中的应用
    比较全的log4j 配置
    验证码类
    PHP 兼容 Curl/Socket/Stream 的 HTTP 操作类
    PHP缓存技术
    Fatal error: Call to undefined function curl_init()解决方案
    socket基础
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4393808.html
Copyright © 2011-2022 走看看