• 翻转链表二


    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;
            
        }
    };
  • 相关阅读:
    jQuery UI DatePicker用法和中文设置
    jQuery的ajax方法
    jQuery遍历复杂的JSON数据
    JavaScript面向对象的写法
    jpa
    日志
    全局异常的处理!
    oracle表空间
    plsql的连接配置
    pLsql使用
  • 原文地址:https://www.cnblogs.com/dynas/p/7003801.html
Copyright © 2020-2023  润新知