• 翻转链表二


    Reverse a linked list from position m to n.

     Notice

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

    Example

    Given 1->2->3->4->5->NULL, m = 2 and n = 4, return1->4->3->2->5->NULL.

    要注意是否从第一个节点开始翻转,1)是则保存第n+1个节点,进行翻转,然后返回s2)否则保存第m-1个节点,和第n+1个节点,翻转

    /**
     * Definition of singly-linked-list:
     * 
     * class ListNode {
     * public:
     *     int val;
     *     ListNode *next;
     *     ListNode(int val) {
     *        this->val = val;
     *        this->next = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param head: The head of linked list.
         * @param m: The start position need to reverse.
         * @param n: The end position need to reverse.
         * @return: The new head of partial reversed linked list.
         */
        ListNode *reverseBetween(ListNode *head, int m, int n) {
            // write your code here
            int i = m;
            int j = n - m;
            ListNode *p = head;
            int count = 0;
            while(p != NULL)
            {
                p = p->next;
                count++;
            }
            if(count < n)return NULL;
            p = head;
            while(i > 2)
            {
                p = p->next;
                i--;
            }
            ListNode *bf = p;
            if(m != 1)p = p->next;
            ListNode *q = p;
            while(j >= 0)
            {
                q = q->next;
                j--;
            }
            ListNode *s = q;
            while(p != q)
            {
                ListNode *tmp = p->next;
                p->next = s;
                s = p;
                p = tmp;
            }
            if(m != 1)
            {
                bf->next = s;
                return head;
            }
            else return s;
            
        }
    };
  • 相关阅读:
    【年度总结】——踏雪留痕
    ios提交程序后出现的各种问题
    c++动态库中使用命名空间的问题
    第八章 网络的时代—网络开发(4)
    USB otg 学习笔记
    servlet_3
    Windows server 2012清除并重建SID
    实时监听输入框值变化:oninput & onpropertychange
    JQuery 自动触发事件
    jquery input change事件
  • 原文地址:https://www.cnblogs.com/dynas/p/7003801.html
Copyright © 2020-2023  润新知