2pointer c++ 9ms


  • 0

    /**

    • 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(k==0||head==NULL)return head;
      int t=0;
      ListNode* cur=head;
      while(cur!=NULL){
      cur=cur->next;
      t++;
      }
      k=k%t;
      if(k==0)return head;
      ListNode* l1=head;
      ListNode* l2=head;
      int tt=0;
      while(tt!=k){
      l2=l2->next;
      tt++;
      }
      while(l2->next!=NULL){
      l2=l2->next;
      l1=l1->next;
      }
      l2->next=head;
      ListNode* tmp=l1->next;
      l1->next=NULL;
      head=tmp;
      return head;
      }
      };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.