(Leetcode)旋转链表

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
例:
1->2->3->4 k=2
3->4->1->2

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode node;
struct ListNode* rotateRight(struct ListNode* head, int k){
    
    
       node* p = head; 
       int L = 0;
       while(p){
    
    
           p = p->next;
           ++L;
       }
       //L为总长
       //L-k%L为编号
       if(!head){
    
    
           return NULL;
       }

       if(k%L == 0){
    
    
           return head;
       }

       node* p1 = head;//负责改变最后节点
       node* p2 = head;//负责记录头节点
       node* p3 = head;//负责改变第L-k%L个节点
       
       while(p1->next!=NULL){
    
    
             p1 = p1->next;
       }
       
        int num = 1; 
        while(num < L-(k%L)){
    
    
            p3 = p3->next;
            ++num;
        }
       
        node* newhead = p3->next;
        p3->next = NULL;
        p1->next = p2;

        return newhead;


}

猜你喜欢

转载自blog.csdn.net/qq_52001969/article/details/113372304