Rotate List

来源:互联网 发布:语音识别 python 编辑:程序博客网 时间:2024/06/04 19:19

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

求出长度L,将tail指针移到最后一个节点位置,tail的下一个节点为头节点,这样就形成了环。用ptr指针找到L-k-1的位置,即3的位置,将ptr(3)的下一个节点赋值给head,并将NULL赋值给ptr(3)的下一个节点,这样就成功断开了环。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *rotateRight(ListNode *head, int k) {        if(head==NULL)return NULL;        if (k==0)return head;       ListNode *ptr=head,*tail=head;       int l=0;       while(ptr){           tail=ptr; //tail移动到最后一个位置。           ptr=ptr->next;           l++;       }       tail->next=head; //形成环       ptr=head;  //回到头节点处       k=k%l;       for(int i=0;i<l-k-1;i++)ptr=ptr->next;  //找到3       head=ptr->next;  //4赋值给头节点       ptr->next=NULL;  //3的下一个节点为空       return head;                   }};

0 0