Reversal of the specified interval in the Niuke linked list

describe

Reversing the interval between the m position and the n position of a linked list whose number of nodes is size requires time complexity O(n) and space complexity O(1).
For example:
the given linked list is 1→2→3→4→5→NULL, m=2,n=4
returns 1\to 4\to 3\to 2\to 5\to NULL1→4→3→2→ 5→NULL.
 

Data range: Linked list length 0<size≤1000, 0<m≤n≤size, the value of each node in the linked list satisfies ∣val∣≤1000

Requirements: time complexity O(n), space complexity O(n)

Advanced: time complexity O(n), space complexity O(1)

Example 1

enter:

{1,2,3,4,5},2,4

Copy return value:

{1,4,3,2,5}

copy

Example 2

enter:

{5},1,1

Copy return value:

{5}

Solution (c):

Swap values ​​using the nodes pointed to by two pointers

code:

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @param m int整型 
 * @param n int整型 
 * @return ListNode类
 */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
    // write code here
    if(m==n) return head;
    struct ListNode *p1,*p2;
    while(m<n){
        p2=p1=head;
        int val;
        for(int i=1;i<m;i++){
            p1=p1->next;
        }
         for(int i=1;i<n;i++){
            p2=p2->next;
        }
        val=p1->val;
        p1->val=p2->val;
        p2->val=val;
        
        n--;
        m++;    
    }
    return head;
}

Guess you like

Origin blog.csdn.net/weixin_53630942/article/details/124161239