LeetCode | Rotate List

来源:互联网 发布:大学网络诋毁严正声明 编辑:程序博客网 时间:2024/06/06 04:57

一开始想错了,以为要在k的位置旋转
其实是要循环滚动地推k次,比如
[1,2]
2
结果应当为[1,2],以为推一圈又回来了

[1,2]
3
则应当是[2,1]效果和1是一样的

于是加一个mod判断就好了

class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        //空或左侧没有链        if(head==NULL || head->next==NULL) return head;        ListNode* new_head;        ListNode root(head->val-1);        root.next=head;        ListNode* t=head;        int count=0;        while(t!=NULL){            count++;            t=t->next;        }        //找出要推多少次        k%=count;        if(k==0) return head;        k=count-k;        ListNode* pre=&root;        t=head;        for(count=0;t!=NULL;pre=pre->next,t=t->next,count++){            if(count==k){                new_head=t;                // //获取最后一个节点                ListNode* temp=t;                while(temp->next!=NULL) temp=temp->next;                //连接尾部到头部                temp->next=root.next;                pre->next=NULL;                break;            }        }        return new_head;    }};

其实代码可以优雅一点

      //空或左侧没有链      if(head==NULL || head->next==NULL) return head;      ListNode* new_head;      ListNode* t=head;      int count=1;      while(t->next!=NULL){          count++;          t=t->next;      }      //找出要推多少次      k%=count;      if(k==0) return head;      k=count-k;      //连接尾部到头,在前面遍历到最后的时候,就可以保留这个指针      t->next=head;      for(count=0;t->next!=NULL;t=t->next,count++){          if(count==k){              new_head=t->next;              t->next=NULL;              break;          }      }      return new_head;
0 0